{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "machine_shape": "hm",
      "gpuType": "A100"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU",
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "bd6b607607d34e3c96de67f9a103f19d": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HBoxModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_db9863f966f24e6fad90dc2e6acae785",
              "IPY_MODEL_50a29d3705bb49d986f548374fef81bc",
              "IPY_MODEL_d2ca4d5e2863449ba87ceb117e3df7da"
            ],
            "layout": "IPY_MODEL_3031182ea08a43e2a75d12d67ceef101"
          }
        },
        "db9863f966f24e6fad90dc2e6acae785": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_46aa4f53040c485387ae03dbc195b34b",
            "placeholder": "​",
            "style": "IPY_MODEL_30bd5d604a7041e9ab193e34be502137",
            "value": "100%"
          }
        },
        "50a29d3705bb49d986f548374fef81bc": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "FloatProgressModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_ed7ee81cf876476ebcd6c6d29b954de4",
            "max": 1425741623,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_3528f43e1f594fa6a65ae43a926e9d95",
            "value": 1425741623
          }
        },
        "d2ca4d5e2863449ba87ceb117e3df7da": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_27281ae3d5d649829478a230b68bca47",
            "placeholder": "​",
            "style": "IPY_MODEL_f2764b194d4e478f97ae5e09f4afb86c",
            "value": " 1.43G/1.43G [00:16&lt;00:00, 87.7MiB/s]"
          }
        },
        "3031182ea08a43e2a75d12d67ceef101": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "46aa4f53040c485387ae03dbc195b34b": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "30bd5d604a7041e9ab193e34be502137": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "ed7ee81cf876476ebcd6c6d29b954de4": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "3528f43e1f594fa6a65ae43a926e9d95": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "ProgressStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "27281ae3d5d649829478a230b68bca47": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "f2764b194d4e478f97ae5e09f4afb86c": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "b5271fc8f29a469696c63aa94f4c66c8": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HBoxModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_6892e1bb32de4655bd093e50aad979b9",
              "IPY_MODEL_56ff1bf94fac41e2a4bfe6c642db64b9",
              "IPY_MODEL_ee15e4b938df499da5b1d2838552962f"
            ],
            "layout": "IPY_MODEL_b5dd37fa45c24680b93c21c1969490f2"
          }
        },
        "6892e1bb32de4655bd093e50aad979b9": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_df2385efc48a411c8e3584c954f23a26",
            "placeholder": "​",
            "style": "IPY_MODEL_63bb98eab8c74dfabea98b85ff397b77",
            "value": "100%"
          }
        },
        "56ff1bf94fac41e2a4bfe6c642db64b9": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "FloatProgressModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_cdbb5e7a249c436b809e125f496eb82e",
            "max": 594036,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_3b4d2cf14f8c496ab740a2485155442b",
            "value": 594036
          }
        },
        "ee15e4b938df499da5b1d2838552962f": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_59dd159940064a309eb1cad67d5faa7a",
            "placeholder": "​",
            "style": "IPY_MODEL_f84bb79f52664a91b1a6ee637281c285",
            "value": " 594k/594k [00:00&lt;00:00, 14.0MiB/s]"
          }
        },
        "b5dd37fa45c24680b93c21c1969490f2": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "df2385efc48a411c8e3584c954f23a26": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "63bb98eab8c74dfabea98b85ff397b77": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "cdbb5e7a249c436b809e125f496eb82e": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "3b4d2cf14f8c496ab740a2485155442b": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "ProgressStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "59dd159940064a309eb1cad67d5faa7a": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "f84bb79f52664a91b1a6ee637281c285": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "cf8262210b7c42bc8db80e1a102acf19": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HBoxModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_509c0ac5a7624e2bb8618b978c8a80dc",
              "IPY_MODEL_56c17b10c28c4fa9a6db05aa60a71f5e",
              "IPY_MODEL_4b85c54d069e4a8d87520dbdad4c2c89"
            ],
            "layout": "IPY_MODEL_6537feb3ffd24d2ea90b27a7a0a1aeb0"
          }
        },
        "509c0ac5a7624e2bb8618b978c8a80dc": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_4e2585503cca48f8a0428cc62d02e5f1",
            "placeholder": "​",
            "style": "IPY_MODEL_b6ea52fd1054458e9458865f8f40ff84",
            "value": "config.json: 100%"
          }
        },
        "56c17b10c28c4fa9a6db05aa60a71f5e": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "FloatProgressModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_d70cc590fb28457b9ca7f74d8aa425f1",
            "max": 694,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_a9116211ec3d407d9278f744d41507e6",
            "value": 694
          }
        },
        "4b85c54d069e4a8d87520dbdad4c2c89": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_d706ec4068874b6eb52918afad80982e",
            "placeholder": "​",
            "style": "IPY_MODEL_9c7b2917eb984de88aa6dbdec1bfa9cb",
            "value": " 694/694 [00:00&lt;00:00, 52.6kB/s]"
          }
        },
        "6537feb3ffd24d2ea90b27a7a0a1aeb0": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "4e2585503cca48f8a0428cc62d02e5f1": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "b6ea52fd1054458e9458865f8f40ff84": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "d70cc590fb28457b9ca7f74d8aa425f1": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "a9116211ec3d407d9278f744d41507e6": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "ProgressStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "d706ec4068874b6eb52918afad80982e": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "9c7b2917eb984de88aa6dbdec1bfa9cb": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "c69abb9efb6b411fa4ee31b0c1910bae": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HBoxModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_1170d27bc06e48bc985700e1703887b3",
              "IPY_MODEL_6264397e6794478fa54e161f4434cc8b",
              "IPY_MODEL_e5acc8060d7c4d25b6c13bb486eb5c39"
            ],
            "layout": "IPY_MODEL_6ff11b9092db4dab98a68505955a612c"
          }
        },
        "1170d27bc06e48bc985700e1703887b3": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_b9f3902a7a844da0ab7d9bf5c2869db7",
            "placeholder": "​",
            "style": "IPY_MODEL_86fa6d3c75e94c109ca0d44ddc7cb6e4",
            "value": "pytorch_model.bin: 100%"
          }
        },
        "6264397e6794478fa54e161f4434cc8b": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "FloatProgressModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_4d7f1a3f6c044343a096951ed2a58603",
            "max": 597257159,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_ef324ed1c14d4e9aac3312ed637f5789",
            "value": 597257159
          }
        },
        "e5acc8060d7c4d25b6c13bb486eb5c39": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_d19fd3e721b84b37b2f4da2bf03008de",
            "placeholder": "​",
            "style": "IPY_MODEL_5d3d80342c864f419e64a323051e3509",
            "value": " 597M/597M [00:02&lt;00:00, 299MB/s]"
          }
        },
        "6ff11b9092db4dab98a68505955a612c": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "b9f3902a7a844da0ab7d9bf5c2869db7": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "86fa6d3c75e94c109ca0d44ddc7cb6e4": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "4d7f1a3f6c044343a096951ed2a58603": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "ef324ed1c14d4e9aac3312ed637f5789": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "ProgressStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "d19fd3e721b84b37b2f4da2bf03008de": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "5d3d80342c864f419e64a323051e3509": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        }
      }
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# Installations\n",
        "\n",
        "The installation is mostly automated.\n",
        "\n",
        "A file in the same directory named \"thesis_ro\" will be required, which should contain your GitHub read-only token.\n",
        "\n",
        "The file has one line:\n",
        "\n",
        "\n",
        "`echo \"GITHUB_PERSONAL_ACCESS_TOKEN=\"ghp_...\" > thesis_ro`"
      ],
      "metadata": {
        "id": "4-p_B7FGB9mg"
      }
    },
    {
      "cell_type": "markdown",
      "source": [],
      "metadata": {
        "id": "QZT7W5H2hezF"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        ">[Installations](#scrollTo=4-p_B7FGB9mg)\n",
        "\n",
        ">[Setup data](#scrollTo=b7jMEfm3CAp1)\n",
        "\n",
        ">[Train custom Tokenizer with complex dataset](#scrollTo=dAYGIiUlCQM9)\n",
        "\n",
        ">[Download dataset to use](#scrollTo=RtdpdugyCl9v)\n",
        "\n",
        ">[ETL dataset](#scrollTo=wk7RQHMuCxjr)\n",
        "\n",
        ">[Max token length](#scrollTo=QdLFssPYC-oG)\n",
        "\n",
        ">[Load LinFormer with max. token length](#scrollTo=ARRqrF8XDG6_)\n",
        "\n",
        ">[Vectorize the text column in that DataFrame](#scrollTo=AzxrG_RmDLr1)\n",
        "\n",
        ">[Convert the vectors to a NumPy array for statistical analysis](#scrollTo=3Gxep-miEAVm)\n",
        "\n",
        ">[UMAP dimensionality check - scattered or clustered?](#scrollTo=zZVCSpvsEJIq)\n",
        "\n",
        ">[Silhouette score via KMeans clustering](#scrollTo=56wtMVhhEVzf)\n",
        "\n",
        ">[Distribution of the Cosine similarity](#scrollTo=8yhTWsSnEl30)\n",
        "\n",
        ">[Comparison model: LongFormer](#scrollTo=FmwKV-BK-rKX)\n",
        "\n",
        ">[Initialize and use LongFormer with the same pre-trained Tokenizer](#scrollTo=J6REcr7hE1xz)\n",
        "\n",
        ">[Approaching Quantile Transoformer for feature scaling for LinFormer model vectors](#scrollTo=SxhOQqiHhPju)\n",
        "\n",
        ">[Quantile Transformer vs. Standard Scaler for feature scaling](#scrollTo=kgdy9N8lhEaF)\n",
        "\n"
      ],
      "metadata": {
        "colab_type": "toc",
        "id": "V-wAtykHhidb"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "5QU9CtLHsJr_"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "import os\n",
        "import subprocess\n",
        "\n",
        "IN_COLAB = 'google.colab' in sys.modules\n",
        "\n",
        "if not IN_COLAB:\n",
        "  pass\n",
        "\n",
        "else:\n",
        "  subprocess.run('''\n",
        "    source <(curl -s https://raw.githubusercontent.com/norandom/log2ml/main/dependencies/install.sh)\n",
        "    ''',\n",
        "    shell=True, check=True, executable='/bin/bash')\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Setup data\n",
        "\n",
        "The data setup is automated, based on GitHub release files. Kaggle or HuggingFace releases are for later, once the work has been completed."
      ],
      "metadata": {
        "id": "b7jMEfm3CAp1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from dotenv import load_dotenv\n",
        "import os\n",
        "\n",
        "load_dotenv(\"thesis_ro\", verbose=True)  # take environment variables from the file\n",
        "token = os.getenv('GITHUB_PERSONAL_ACCESS_TOKEN')\n",
        "if len(token) > 0:\n",
        "  print(\"ok\")\n",
        "else:\n",
        "  print(\"no token\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "B4wCRu4DAC0Z",
        "outputId": "e5383477-f981-4a9e-d448-6707b4f73737"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "ok\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from github import Github\n",
        "import requests\n",
        "from tqdm.notebook import tqdm\n",
        "\n",
        "\n",
        "def get_specific_file_from_tagged_release(token, repo_name, tag_name, filename):\n",
        "    g = Github(token)\n",
        "    repo = g.get_repo(repo_name)\n",
        "    releases = repo.get_releases()\n",
        "\n",
        "    for release in releases:\n",
        "        if release.tag_name == tag_name:\n",
        "            for asset in release.get_assets():\n",
        "                if asset.name == filename:\n",
        "                    return asset.url\n",
        "    print(\"File not found. Try get_specific_file_from_latest_release() instead.\")\n",
        "    return None\n",
        "\n",
        "def get_specific_file_from_latest_release(token, repo_name, filename):\n",
        "    g = Github(token)\n",
        "    repo = g.get_repo(repo_name)\n",
        "    release = repo.get_latest_release()\n",
        "\n",
        "    for asset in release.get_assets():\n",
        "        if asset.name == filename:\n",
        "            return asset.url  # Use asset.url which points to API URL needing headers\n",
        "\n",
        "def download_file(url, token, save_path):\n",
        "    headers = {'Authorization': f'token {token}', 'Accept': 'application/octet-stream'}\n",
        "    # First request to handle GitHub's redirection and authentication properly\n",
        "    with requests.get(url, headers=headers, stream=True) as initial_response:\n",
        "        initial_response.raise_for_status()  # Ensure the initial request is successful\n",
        "        # Follow redirection if necessary, maintaining headers\n",
        "        if initial_response.history:\n",
        "            url = initial_response.url  # Updated URL after redirection\n",
        "\n",
        "        # Now, proceed with downloading the file\n",
        "        with requests.get(url, headers=headers, stream=True) as response:\n",
        "            response.raise_for_status()\n",
        "            total_size_in_bytes = int(response.headers.get('content-length', 0))\n",
        "            block_size = 1024\n",
        "\n",
        "            progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True)\n",
        "            with open(save_path, 'wb') as file:\n",
        "                for data in response.iter_content(block_size):\n",
        "                    progress_bar.update(len(data))\n",
        "                    file.write(data)\n",
        "            progress_bar.close()\n",
        "\n",
        "            if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:\n",
        "                print(\"ERROR, something went wrong\")\n",
        "            else:\n",
        "                print(f\"File downloaded successfully and saved as {save_path}\")\n",
        "\n",
        "# Your GitHub token\n",
        "github_token = token\n",
        "\n",
        "# Repository name\n",
        "repository_name = \"norandom/log2ml\"\n",
        "\n",
        "# File name to search for\n",
        "file_name = \"lab_logs_normal_activity_may_11_2024.csv\"\n",
        "\n",
        "# Get the download URL of the specific file\n",
        "# download_url = get_specific_file_from_latest_release(github_token, repository_name, file_name)\n",
        "download_url = get_specific_file_from_tagged_release(github_token, repository_name, \"foundations\", file_name)\n",
        "print(download_url)\n",
        "\n",
        "if download_url:\n",
        "    local_file_path = \"lab_logs_normal_activity_may_11_2024.csv\"\n",
        "    download_file(download_url, github_token, local_file_path)\n",
        "else:\n",
        "    print(\"File not found.\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 85,
          "referenced_widgets": [
            "bd6b607607d34e3c96de67f9a103f19d",
            "db9863f966f24e6fad90dc2e6acae785",
            "50a29d3705bb49d986f548374fef81bc",
            "d2ca4d5e2863449ba87ceb117e3df7da",
            "3031182ea08a43e2a75d12d67ceef101",
            "46aa4f53040c485387ae03dbc195b34b",
            "30bd5d604a7041e9ab193e34be502137",
            "ed7ee81cf876476ebcd6c6d29b954de4",
            "3528f43e1f594fa6a65ae43a926e9d95",
            "27281ae3d5d649829478a230b68bca47",
            "f2764b194d4e478f97ae5e09f4afb86c"
          ]
        },
        "id": "ORNebW15Bb4B",
        "outputId": "58583b66-046e-4b57-c892-f877d5fa55ad"
      },
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "https://api.github.com/repos/norandom/log2ml/releases/assets/168248751\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "  0%|          | 0.00/1.43G [00:00<?, ?iB/s]"
            ],
            "application/vnd.jupyter.widget-view+json": {
              "version_major": 2,
              "version_minor": 0,
              "model_id": "bd6b607607d34e3c96de67f9a103f19d"
            }
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "File downloaded successfully and saved as lab_logs_normal_activity_may_11_2024.csv\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Train custom Tokenizer with complex dataset\n",
        "\n",
        "The dataset contains security-agent telemetry from MS Sysmon.\n",
        "Therefore a custom Tokenizer is needed, given that the content isn't 100% natural language.\n",
        "\n",
        "BPE stands for Byte Pair Encoding Tokenization\n",
        "\n",
        "\"It’s used by a lot of Transformer models, including GPT, GPT-2, RoBERTa, BART, and DeBERTa.\" [1]\n",
        "\n",
        "Given that LongFormer and Linformer are Transformer Network architectures, BPE is a compatible choice.\n",
        "\n",
        "Parsing the data as a CSV or colon-separated values isn't preferable, because the implementation goal is a generically reuseable log- / trace-data vectorizer. Approaches like bag-of-words or one-hot-encoding may become too specific to the data.\n",
        "\n",
        "[1] https://huggingface.co/learn/nlp-course/en/chapter6/5"
      ],
      "metadata": {
        "id": "dAYGIiUlCQM9"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from tokenizers import Tokenizer\n",
        "from tokenizers.models import BPE\n",
        "from tokenizers.trainers import BpeTrainer\n",
        "from tokenizers.pre_tokenizers import Whitespace\n",
        "\n",
        "# Initialize the tokenizer\n",
        "tokenizer = Tokenizer(BPE())\n",
        "\n",
        "# Setup pre-tokenizer\n",
        "tokenizer.pre_tokenizer = Whitespace()\n",
        "\n",
        "# Setup trainer\n",
        "trainer = BpeTrainer(\n",
        "    vocab_size=30000,\n",
        "    min_frequency=2,\n",
        "    special_tokens=[\"=\", \":\", \",\", \"\\\"\", \"\\'\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\"],\n",
        "    show_progress=True\n",
        ")\n",
        "\n",
        "# Train the tokenizer on your log data\n",
        "tokenizer.train(files=[\"lab_logs_normal_activity_may_11_2024.csv\"], trainer=trainer)\n",
        "\n",
        "# Save the tokenizer\n",
        "tokenizer.save(\"log_tokenizer.json\")"
      ],
      "metadata": {
        "id": "9A2nD4deq8lO"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Test with a message\n",
        "\n",
        "By avoid time or other variant series data we can avoid noisy vectors."
      ],
      "metadata": {
        "id": "pszMjefAiWmS"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "log_text = \"\"\"\n",
        "Registry value set (rule: RegistryEvent),\"Registry value set:\n",
        "RuleName: InvDB-Ver\n",
        "EventType: SetValue\n",
        "UtcTime: 2024-07-28 15:09:33.716\n",
        "ProcessGuid: {18e8265a-5ee4-66a6-5400-000000004400}\n",
        "ProcessId: 4032\n",
        "Image: C:\\Windows\\System32\\svchost.exe\n",
        "TargetObject: \\REGISTRY\\A\\{90cbbb87-bac4-4fa3-1d8b-b1a042a75259}\\Root\\InventoryApplicationFile\\ie4uinit.exe|874b2700383dd346\\BinProductVersion\n",
        "Details: 11.0.19041.4648\"\n",
        "\"\"\"\n",
        "\n",
        "# Tokenize your log_text\n",
        "output = tokenizer.encode(log_text)\n",
        "\n",
        "# Print the tokens\n",
        "print(output.tokens)\n",
        "\n",
        "# If you want to get the IDs of the tokens\n",
        "print(output.ids)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "LTQyGEuZMhdS",
        "outputId": "8e4f07ba-5f5e-4e42-afc0-4634afd7df7c"
      },
      "execution_count": 33,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "['2024', '-', '07', '-', '28T', '15', ':', '09', ':', '33', '.', '716Z', ',', 'win10', ',', 'fe80', ':', ':', 'c', '1af', ':', '35', 'de', ':', '600', '6', ':', 'd4c', 'f', ',', 'information', ',', '13', ',', 'Registry', 'value', 'set', '(', 'rule', ':', 'RegistryEvent', ')', ',', '\"', 'Registry', 'value', 'set', ':', 'RuleName', ':', 'InvDB', '-', 'Ver', 'EventType', ':', 'SetValue', 'UtcTime', ':', '2024', '-', '07', '-', '28', '15', ':', '09', ':', '33', '.', '716', 'ProcessGuid', ':', '{', '18e8265a', '-', '5e', 'e4', '-', '6', '6a', '6', '-', '5400', '-', '00000000', '4400', '}', 'ProcessId', ':', '4032', 'Image', ':', 'C', ':', '\\\\', 'Windows', '\\\\', 'System32', '\\\\', 'svchost', '.', 'exe', 'TargetObject', ':', '\\\\', 'REGISTRY', '\\\\', 'A', '\\\\', '{', '90', 'cbb', 'b87', '-', 'bac', '4', '-', '4fa', '3', '-', '1d', '8b', '-', 'b1a', '042', 'a7', '525', '9', '}', '\\\\', 'Root', '\\\\', 'InventoryApplicationFile', '\\\\', 'ie4uinit', '.', 'exe', '|', '87', '4b', '2700', '38', '3d', 'd3', '46', '\\\\', 'BinProductVersion', 'Details', ':', '11', '.', '0', '.', '19041', '.', '4648', '\"']\n",
            "[789, 18, 282, 18, 9118, 429, 1, 451, 1, 733, 19, 20558, 2, 229, 2, 426, 1, 1, 68, 29307, 1, 292, 352, 1, 1150, 27, 1, 22018, 71, 2, 437, 2, 591, 2, 1196, 795, 987, 5, 865, 1, 2644, 6, 2, 3, 1196, 795, 987, 1, 1324, 1, 4115, 18, 5731, 4108, 1, 2763, 1112, 1, 789, 18, 282, 18, 316, 429, 1, 451, 1, 733, 19, 26125, 1450, 1, 9, 444, 18, 1120, 1747, 18, 27, 898, 27, 18, 22096, 18, 379, 14576, 10, 1089, 1, 27452, 1041, 1, 38, 1, 62, 176, 62, 307, 62, 915, 19, 260, 4107, 1, 62, 3071, 62, 36, 62, 9, 322, 10902, 10887, 18, 10941, 25, 18, 6459, 24, 18, 360, 2379, 18, 11383, 14573, 766, 7844, 30, 10, 62, 2675, 62, 3349, 62, 20723, 19, 260, 92, 799, 489, 2805, 256, 2276, 1360, 308, 62, 5983, 2001, 1, 318, 19, 21, 19, 326, 19, 19526, 3]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Download dataset to use\n",
        "\n",
        "The analysis dataset has less complex data.\n",
        "Variant series data has been removed."
      ],
      "metadata": {
        "id": "RtdpdugyCl9v"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# File name to search for\n",
        "file_name = \"lab_logs_blindtest_activity_june_25_2024.csv\"\n",
        "\n",
        "# Get the download URL of the specific file\n",
        "# download_url = get_specific_file_from_latest_release(github_token, repository_name, file_name)\n",
        "download_url = get_specific_file_from_tagged_release(github_token, repository_name, \"foundations\", file_name)\n",
        "print(download_url)\n",
        "\n",
        "if download_url:\n",
        "    local_file_path = file_name\n",
        "    download_file(download_url, github_token, local_file_path)\n",
        "else:\n",
        "    print(\"File not found.\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 85,
          "referenced_widgets": [
            "b5271fc8f29a469696c63aa94f4c66c8",
            "6892e1bb32de4655bd093e50aad979b9",
            "56ff1bf94fac41e2a4bfe6c642db64b9",
            "ee15e4b938df499da5b1d2838552962f",
            "b5dd37fa45c24680b93c21c1969490f2",
            "df2385efc48a411c8e3584c954f23a26",
            "63bb98eab8c74dfabea98b85ff397b77",
            "cdbb5e7a249c436b809e125f496eb82e",
            "3b4d2cf14f8c496ab740a2485155442b",
            "59dd159940064a309eb1cad67d5faa7a",
            "f84bb79f52664a91b1a6ee637281c285"
          ]
        },
        "id": "mjrM6gVOGfHq",
        "outputId": "ed833527-a554-48eb-f2a5-6d166e4eb88e"
      },
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "https://api.github.com/repos/norandom/log2ml/releases/assets/175872904\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "  0%|          | 0.00/594k [00:00<?, ?iB/s]"
            ],
            "application/vnd.jupyter.widget-view+json": {
              "version_major": 2,
              "version_minor": 0,
              "model_id": "b5271fc8f29a469696c63aa94f4c66c8"
            }
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "File downloaded successfully and saved as lab_logs_blindtest_activity_june_25_2024.csv\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# ETL dataset\n",
        "\n",
        "ETL stands for Extract, Transform, Load. Polars is used as an ETL framework. It allows DataFrame operations, similar to Pandas."
      ],
      "metadata": {
        "id": "wk7RQHMuCxjr"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import polars as pl\n",
        "\n",
        "csv_file_path = 'lab_logs_blindtest_activity_june_25_2024.csv'\n",
        "\n",
        "# Load the CSV file into a DataFrame\n",
        "df = pl.read_csv(csv_file_path)\n",
        "\n",
        "# Show the DataFrame to confirm it's loaded correctly\n",
        "print(df)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "4ZzWtIgFxBJS",
        "outputId": "c757f28a-94c4-4d2b-cfc8-33e4c8b3889f"
      },
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "shape: (1_027, 5)\n",
            "┌───────┬─────────────┬─────────────────┬───────────────────────────────────┬─────────────────────┐\n",
            "│ index ┆ log.level   ┆ winlog.event_id ┆ winlog.task                       ┆ filtered_message    │\n",
            "│ ---   ┆ ---         ┆ ---             ┆ ---                               ┆ ---                 │\n",
            "│ i64   ┆ str         ┆ i64             ┆ str                               ┆ str                 │\n",
            "╞═══════╪═════════════╪═════════════════╪═══════════════════════════════════╪═════════════════════╡\n",
            "│ 0     ┆ information ┆ 10              ┆ Process accessed (rule: ProcessA… ┆ Process accessed:   │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: -         │\n",
            "│       ┆             ┆                 ┆                                   ┆ So…                 │\n",
            "│ 1     ┆ information ┆ 10              ┆ Process accessed (rule: ProcessA… ┆ Process accessed:   │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: -         │\n",
            "│       ┆             ┆                 ┆                                   ┆ So…                 │\n",
            "│ 2     ┆ information ┆ 1               ┆ Process Create (rule: ProcessCre… ┆ Process Create:     │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: -         │\n",
            "│       ┆             ┆                 ┆                                   ┆ Proc…               │\n",
            "│ 3     ┆ information ┆ 13              ┆ Registry value set (rule: Regist… ┆ Registry value set: │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: Ta…       │\n",
            "│ …     ┆ …           ┆ …               ┆ …                                 ┆ …                   │\n",
            "│ 1023  ┆ information ┆ 10              ┆ Process accessed (rule: ProcessA… ┆ Process accessed:   │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: -         │\n",
            "│       ┆             ┆                 ┆                                   ┆ So…                 │\n",
            "│ 1024  ┆ information ┆ 1               ┆ Process Create (rule: ProcessCre… ┆ Process Create:     │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: -         │\n",
            "│       ┆             ┆                 ┆                                   ┆ Proc…               │\n",
            "│ 1025  ┆ information ┆ 22              ┆ Dns query (rule: DnsQuery)        ┆ Dns query:          │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: -         │\n",
            "│       ┆             ┆                 ┆                                   ┆ ProcessId…          │\n",
            "│ 1026  ┆ information ┆ 1               ┆ Process Create (rule: ProcessCre… ┆ Process Create:     │\n",
            "│       ┆             ┆                 ┆                                   ┆ RuleName: -         │\n",
            "│       ┆             ┆                 ┆                                   ┆ Proc…               │\n",
            "└───────┴─────────────┴─────────────────┴───────────────────────────────────┴─────────────────────┘\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import re\n",
        "\n",
        "# Extract relevant information using regular expressions\n",
        "def extract_info(text):\n",
        "    image = re.search(r\"Image: (.*?\\.exe)\", text, re.IGNORECASE)\n",
        "    target_filename = re.search(r\"TargetFilename: (.*?\\.exe)\", text, re.IGNORECASE)\n",
        "    return {\n",
        "        \"image\": image.group(1) if image else \"\",\n",
        "        \"target_filename\": target_filename.group(1) if target_filename else \"\",\n",
        "        \"text\": text\n",
        "    }\n",
        "\n",
        "# Apply extraction to the Polars DataFrame using map_elements\n",
        "better_columns_df = df.with_columns(\n",
        "    pl.col(\"filtered_message\").map_elements(lambda x: extract_info(x), return_dtype=pl.Object).alias(\"extracted_info\")\n",
        ")\n",
        "\n",
        "# Extract fields from the extracted_info column using map_elements with return_dtype\n",
        "better_columns_df = better_columns_df.with_columns(\n",
        "    pl.col(\"extracted_info\").map_elements(lambda x: x['image'], return_dtype=pl.Utf8).alias(\"image\"),\n",
        "    pl.col(\"extracted_info\").map_elements(lambda x: x['target_filename'], return_dtype=pl.Utf8).alias(\"target_filename\"),\n",
        "    pl.col(\"extracted_info\").map_elements(lambda x: x['text'], return_dtype=pl.Utf8).alias(\"text\")\n",
        ").drop(\"extracted_info\")\n",
        "\n",
        "print(better_columns_df)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "HoknJOrTZC7V",
        "outputId": "6525ea8b-f1f8-4ac7-9f7f-9e13ea6856d7"
      },
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "shape: (1_027, 8)\n",
            "┌───────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┐\n",
            "│ index ┆ log.level  ┆ winlog.eve ┆ winlog.tas ┆ filtered_m ┆ image      ┆ target_fil ┆ text       │\n",
            "│ ---   ┆ ---        ┆ nt_id      ┆ k          ┆ essage     ┆ ---        ┆ ename      ┆ ---        │\n",
            "│ i64   ┆ str        ┆ ---        ┆ ---        ┆ ---        ┆ str        ┆ ---        ┆ str        │\n",
            "│       ┆            ┆ i64        ┆ str        ┆ str        ┆            ┆ str        ┆            │\n",
            "╞═══════╪════════════╪════════════╪════════════╪════════════╪════════════╪════════════╪════════════╡\n",
            "│ 0     ┆ informatio ┆ 10         ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆ accessed:  ┆ \\system32\\ ┆            ┆ accessed:  │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ svchost.ex ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆ -          ┆ e          ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ So…        ┆            ┆            ┆ So…        │\n",
            "│ 1     ┆ informatio ┆ 10         ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆ accessed:  ┆ \\system32\\ ┆            ┆ accessed:  │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ svchost.ex ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆ -          ┆ e          ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ So…        ┆            ┆            ┆ So…        │\n",
            "│ 2     ┆ informatio ┆ 1          ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ Create     ┆ Create:    ┆ \\servicing ┆            ┆ Create:    │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆ RuleName:  ┆ \\TrustedIn ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆ -          ┆ st…        ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ Proc…      ┆            ┆            ┆ Proc…      │\n",
            "│ 3     ┆ informatio ┆ 13         ┆ Registry   ┆ Registry   ┆ C:\\Windows ┆            ┆ Registry   │\n",
            "│       ┆ n          ┆            ┆ value set  ┆ value set: ┆ \\servicing ┆            ┆ value set: │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ \\TrustedIn ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ Regist…    ┆ Ta…        ┆ st…        ┆            ┆ Ta…        │\n",
            "│ …     ┆ …          ┆ …          ┆ …          ┆ …          ┆ …          ┆ …          ┆ …          │\n",
            "│ 1023  ┆ informatio ┆ 10         ┆ Process    ┆ Process    ┆ C:\\Program ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆ accessed:  ┆ Files (x86 ┆            ┆ accessed:  │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ )\\Microsof ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆ -          ┆ t…         ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ So…        ┆            ┆            ┆ So…        │\n",
            "│ 1024  ┆ informatio ┆ 1          ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ Create     ┆ Create:    ┆ \\System32\\ ┆            ┆ Create:    │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆ RuleName:  ┆ taskhostw. ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆ -          ┆ ex…        ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ Proc…      ┆            ┆            ┆ Proc…      │\n",
            "│ 1025  ┆ informatio ┆ 22         ┆ Dns query  ┆ Dns query: ┆            ┆            ┆ Dns query: │\n",
            "│       ┆ n          ┆            ┆ (rule:     ┆ RuleName:  ┆            ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ DnsQuery)  ┆ -          ┆            ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ ProcessId… ┆            ┆            ┆ ProcessId… │\n",
            "│ 1026  ┆ informatio ┆ 1          ┆ Process    ┆ Process    ┆ C:\\Program ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ Create     ┆ Create:    ┆ Files\\RUXI ┆            ┆ Create:    │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆ RuleName:  ┆ M\\PLUGSche ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆ -          ┆ d…         ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ Proc…      ┆            ┆            ┆ Proc…      │\n",
            "└───────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┘\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Max token length\n",
        "\n",
        "Selecting models which can deal with the long Sysmon agent messages is a key design requirement for the ML pipeline. Therefore the maximum token lengt"
      ],
      "metadata": {
        "id": "QdLFssPYC-oG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from tokenizers import Tokenizer\n",
        "\n",
        "# Load the custom tokenizer\n",
        "tokenizer = Tokenizer.from_file(\"log_tokenizer.json\")\n",
        "\n",
        "# Tokenize the messages and calculate total tokens\n",
        "token_lengths = better_columns_df[\"filtered_message\"].map_elements(\n",
        "    lambda x: len(tokenizer.encode(x).ids)\n",
        ")\n",
        "\n",
        "# Get the total input token count\n",
        "total_input_tokens = token_lengths.sum()\n",
        "\n",
        "print(f\"The total number of input tokens in 'filtered_message' column is: {total_input_tokens}\")\n",
        "\n",
        "# Cost calculation\n",
        "input_cost_per_1m_tokens = 10.00  # $10.00 per 1M tokens for input\n",
        "output_cost_per_1m_tokens = 30.00  # $30.00 per 1M tokens for output\n",
        "\n",
        "# Estimate output tokens (this is an assumption, adjust as needed)\n",
        "estimated_output_tokens = total_input_tokens * 0.5  # Assuming output is 50% of input\n",
        "\n",
        "# Calculate costs\n",
        "input_cost = (total_input_tokens / 1_000_000) * input_cost_per_1m_tokens\n",
        "output_cost = (estimated_output_tokens / 1_000_000) * output_cost_per_1m_tokens\n",
        "total_cost = input_cost + output_cost\n",
        "\n",
        "print(\"Reference: OpenAI GPT4-turbo July 2022\")\n",
        "print(f\"Estimated input cost: ${input_cost:.2f}\")\n",
        "print(f\"Estimated output cost: ${output_cost:.2f}\")\n",
        "print(f\"Estimated total cost: ${total_cost:.2f}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "g7lfhJmEckFK",
        "outputId": "c6330ae4-8673-4814-fd45-ef2d25238fbc"
      },
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The total number of input tokens in 'filtered_message' column is: 157897\n",
            "Reference: OpenAI GPT4-turbo July 2022\n",
            "Estimated input cost: $1.58\n",
            "Estimated output cost: $2.37\n",
            "Estimated total cost: $3.95\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Load LinFormer with max. token length"
      ],
      "metadata": {
        "id": "ARRqrF8XDG6_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import torch\n",
        "torch.cuda.empty_cache()"
      ],
      "metadata": {
        "id": "OIXpckDUPZ6C"
      },
      "execution_count": 16,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Linformer parameter 1:1 from the researchers\n",
        "# then the input_size is determined based on the max no. of tokens\n",
        "# the positional embedding flag is on by default\n",
        "\n",
        "from linformer_pytorch import LinformerLM\n",
        "import torch\n",
        "\n",
        "linformer_model = LinformerLM(\n",
        "        num_tokens=30000, # Number of tokens in the LM\n",
        "        input_size=700, # Dimension 1 of the input\n",
        "        channels=64, # Dimension 2 of the input\n",
        "        dim_d=None, # Overwrites the inner dim of the attention heads. If None, sticks with the recommended channels // nhead, as in the \"Attention is all you need\" paper\n",
        "        dim_k=128, # The second dimension of the P_bar matrix from the paper\n",
        "        dim_ff=128, # Dimension in the feed forward network\n",
        "        dropout_ff=0.15, # Dropout for feed forward network\n",
        "        nhead=4, # Number of attention heads\n",
        "        depth=2, # How many times to run the model\n",
        "        dropout=0.1, # How much dropout to apply to P_bar after softmax\n",
        "        activation=\"gelu\", # What activation to use. Currently, only gelu and relu supported, and only on ff network.\n",
        "        checkpoint_level=\"C0\", # What checkpoint level to use. For more information, see below.\n",
        "        parameter_sharing=\"layerwise\", # What level of parameter sharing to use. For more information, see below.\n",
        "        k_reduce_by_layer=0, # Going down `depth`, how much to reduce `dim_k` by, for the `E` and `F` matrices. Will have a minimum value of 1.\n",
        "        full_attention=False, # Use full attention instead, for O(n^2) time and space complexity. Included here just for comparison\n",
        "        include_ff=True, # Whether or not to include the Feed Forward layer\n",
        "        w_o_intermediate_dim=None, # If not None, have 2 w_o matrices, such that instead of `dim*nead,channels`, you have `dim*nhead,w_o_int`, and `w_o_int,channels`\n",
        "        emb_dim=128, # If you want the embedding dimension to be different than the channels for the Linformer\n",
        "        causal=False, # If you want this to be a causal Linformer, where the upper right of the P_bar matrix is masked out.\n",
        "        method=\"learnable\", # The method of how to perform the projection. Supported methods are 'convolution', 'learnable', and 'no_params'\n",
        "        ff_intermediate=None, # See the section below for more information\n",
        "        ).cuda()"
      ],
      "metadata": {
        "id": "BeSmET5qvPCu"
      },
      "execution_count": 17,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Vectorize the text column in that DataFrame"
      ],
      "metadata": {
        "id": "AzxrG_RmDLr1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from tokenizers import Tokenizer\n",
        "import torch\n",
        "import numpy as np\n",
        "import polars as pl\n",
        "\n",
        "# Load the custom tokenizer\n",
        "tokenizer = Tokenizer.from_file(\"log_tokenizer.json\")\n",
        "\n",
        "# Define the device (assuming you're using PyTorch and want to specify CPU or GPU)\n",
        "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
        "\n",
        "def vectorize_text(text):\n",
        "    MAX_LENGTH = 700  # Define the maximum length of tokens for the model\n",
        "\n",
        "    # Tokenize using the custom tokenizer\n",
        "    encoded = tokenizer.encode(text)\n",
        "\n",
        "    # Get token IDs\n",
        "    input_ids = encoded.ids\n",
        "\n",
        "    # Ensure the input_ids length is exactly MAX_LENGTH\n",
        "    input_ids = input_ids[:MAX_LENGTH] if len(input_ids) > MAX_LENGTH else input_ids + [0] * (MAX_LENGTH - len(input_ids))\n",
        "\n",
        "    # Convert to PyTorch tensor and move to the appropriate device\n",
        "    input_ids = torch.tensor([input_ids], dtype=torch.long).to(device)\n",
        "\n",
        "    # Get the model outputs, ensuring the input tensor is the correct size\n",
        "    outputs = linformer_model(input_ids)  # Now passing the tensor directly\n",
        "\n",
        "    # Assuming outputs is the tensor of interest\n",
        "    vector = outputs.mean(dim=1).detach()  # Detach the tensor from the GPU\n",
        "    return vector.cpu().numpy()  # Move tensor back to CPU and convert to numpy\n",
        "\n",
        "# Assuming `better_columns_df` is a Polars DataFrame with a column \"filtered_message\"\n",
        "linformer_vector_df = better_columns_df.with_columns(\n",
        "    pl.col(\"filtered_message\").map_elements(lambda x: vectorize_text(x).flatten(), return_dtype=pl.Object).alias(\"message_vector\")\n",
        ")\n",
        "\n",
        "print(linformer_vector_df)\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "79IKUS-OXEiS",
        "outputId": "cc314d37-884a-4852-c17e-ab7e65777ada"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "shape: (1_027, 9)\n",
            "┌───────┬────────────┬────────────┬────────────┬───┬───────────┬───────────┬───────────┬───────────┐\n",
            "│ index ┆ log.level  ┆ winlog.eve ┆ winlog.tas ┆ … ┆ image     ┆ target_fi ┆ text      ┆ message_v │\n",
            "│ ---   ┆ ---        ┆ nt_id      ┆ k          ┆   ┆ ---       ┆ lename    ┆ ---       ┆ ector     │\n",
            "│ i64   ┆ str        ┆ ---        ┆ ---        ┆   ┆ str       ┆ ---       ┆ str       ┆ ---       │\n",
            "│       ┆            ┆ i64        ┆ str        ┆   ┆           ┆ str       ┆           ┆ object    │\n",
            "╞═══════╪════════════╪════════════╪════════════╪═══╪═══════════╪═══════════╪═══════════╪═══════════╡\n",
            "│ 0     ┆ informatio ┆ 10         ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [ 0.18137 │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆   ┆ s\\system3 ┆           ┆ accessed: ┆ 093 -0.25 │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ 2\\svchost ┆           ┆ RuleName: ┆ 33698     │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆   ┆ .exe      ┆           ┆ -         ┆ -0.0416…  │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ So…       ┆           │\n",
            "│ 1     ┆ informatio ┆ 10         ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [ 0.18577 │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆   ┆ s\\system3 ┆           ┆ accessed: ┆ 585 -0.26 │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ 2\\svchost ┆           ┆ RuleName: ┆ 15168     │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆   ┆ .exe      ┆           ┆ -         ┆ -0.0566…  │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ So…       ┆           │\n",
            "│ 2     ┆ informatio ┆ 1          ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [ 0.32916 │\n",
            "│       ┆ n          ┆            ┆ Create     ┆   ┆ s\\servici ┆           ┆ Create:   ┆ 135 -0.28 │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆   ┆ ng\\Truste ┆           ┆ RuleName: ┆ 799376    │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆   ┆ dInst…    ┆           ┆ -         ┆ -0.0459…  │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Proc…     ┆           │\n",
            "│ 3     ┆ informatio ┆ 13         ┆ Registry   ┆ … ┆ C:\\Window ┆           ┆ Registry  ┆ [ 0.33915 │\n",
            "│       ┆ n          ┆            ┆ value set  ┆   ┆ s\\servici ┆           ┆ value     ┆ 532 -0.29 │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ ng\\Truste ┆           ┆ set:      ┆ 842803    │\n",
            "│       ┆            ┆            ┆ Regist…    ┆   ┆ dInst…    ┆           ┆ RuleName: ┆ -0.0153…  │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Ta…       ┆           │\n",
            "│ …     ┆ …          ┆ …          ┆ …          ┆ … ┆ …         ┆ …         ┆ …         ┆ …         │\n",
            "│ 1023  ┆ informatio ┆ 10         ┆ Process    ┆ … ┆ C:\\Progra ┆           ┆ Process   ┆ [ 0.07160 │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆   ┆ m Files   ┆           ┆ accessed: ┆ 681 -0.26 │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ (x86)\\Mic ┆           ┆ RuleName: ┆ 001436    │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆   ┆ rosoft…   ┆           ┆ -         ┆ -0.0120…  │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ So…       ┆           │\n",
            "│ 1024  ┆ informatio ┆ 1          ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [         │\n",
            "│       ┆ n          ┆            ┆ Create     ┆   ┆ s\\System3 ┆           ┆ Create:   ┆ 0.3071262 │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆   ┆ 2\\taskhos ┆           ┆ RuleName: ┆ -0.313339 │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆   ┆ tw.ex…    ┆           ┆ -         ┆ 6         │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Proc…     ┆ -0.0181…  │\n",
            "│ 1025  ┆ informatio ┆ 22         ┆ Dns query  ┆ … ┆           ┆           ┆ Dns       ┆ [         │\n",
            "│       ┆ n          ┆            ┆ (rule:     ┆   ┆           ┆           ┆ query:    ┆ 0.3430285 │\n",
            "│       ┆            ┆            ┆ DnsQuery)  ┆   ┆           ┆           ┆ RuleName: ┆ -0.288157 │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ -         ┆ 05        │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ ProcessId ┆ -0.0193…  │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ …         ┆           │\n",
            "│ 1026  ┆ informatio ┆ 1          ┆ Process    ┆ … ┆ C:\\Progra ┆           ┆ Process   ┆ [ 0.29110 │\n",
            "│       ┆ n          ┆            ┆ Create     ┆   ┆ m Files\\R ┆           ┆ Create:   ┆ 384 -0.29 │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆   ┆ UXIM\\PLUG ┆           ┆ RuleName: ┆ 604813    │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆   ┆ Sched…    ┆           ┆ -         ┆ -0.0109…  │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Proc…     ┆           │\n",
            "└───────┴────────────┴────────────┴────────────┴───┴───────────┴───────────┴───────────┴───────────┘\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Ensure memory_profiler is installed\n",
        "!pip install -q memory-profiler\n",
        "\n",
        "import timeit\n",
        "from memory_profiler import memory_usage\n",
        "import polars as pl\n",
        "import numpy as np\n",
        "import torch\n",
        "\n",
        "# Function to process the DataFrame and measure memory usage\n",
        "def process_and_measure(df):\n",
        "    # Reset GPU memory peak stats\n",
        "    if torch.cuda.is_available():\n",
        "        torch.cuda.reset_peak_memory_stats()\n",
        "\n",
        "    temp_df = df.with_columns(\n",
        "        pl.col(\"filtered_message\").map_elements(lambda x: vectorize_text(x).flatten(), return_dtype=pl.Object).alias(\"message_vector\")\n",
        "    )\n",
        "\n",
        "    # Get GPU memory usage\n",
        "    gpu_memory_usage = torch.cuda.max_memory_allocated() / (1024 ** 2) if torch.cuda.is_available() else 0\n",
        "    return gpu_memory_usage\n",
        "\n",
        "# Number of times to run the function\n",
        "n_runs = 10\n",
        "\n",
        "# Measure the runtime, CPU, and GPU memory usage over multiple runs\n",
        "runtimes = []\n",
        "cpu_memory_usages = []\n",
        "gpu_memory_usages = []\n",
        "\n",
        "for _ in range(n_runs):\n",
        "    # Measure runtime\n",
        "    runtime = timeit.timeit(lambda: process_and_measure(better_columns_df), number=1)\n",
        "    runtimes.append(runtime)\n",
        "\n",
        "    # Measure CPU memory usage\n",
        "    cpu_mem_usage = memory_usage((process_and_measure, (better_columns_df,)))\n",
        "    cpu_memory_usages.append(max(cpu_mem_usage) - min(cpu_mem_usage))\n",
        "\n",
        "    # Measure GPU memory usage\n",
        "    gpu_mem_usage = process_and_measure(better_columns_df)\n",
        "    gpu_memory_usages.append(gpu_mem_usage)\n",
        "\n",
        "# Calculate average runtime, CPU memory, and GPU memory usage\n",
        "average_runtime = np.mean(runtimes)\n",
        "average_cpu_memory_usage = np.mean(cpu_memory_usages)\n",
        "average_gpu_memory_usage = np.mean(gpu_memory_usages)\n",
        "\n",
        "print(f\"Average runtime over {n_runs} runs: {average_runtime:.6f} seconds\")\n",
        "print(f\"Average CPU memory usage over {n_runs} runs: {average_cpu_memory_usage:.2f} MiB\")\n",
        "print(f\"Average GPU memory usage over {n_runs} runs: {average_gpu_memory_usage:.2f} MiB\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "g8zGXPPsRAoh",
        "outputId": "cdaf812f-935b-4dc5-db31-5aa2593ea24c"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Average runtime over 10 runs: 7.183239 seconds\n",
            "Average CPU memory usage over 10 runs: 116.41 MiB\n",
            "Average GPU memory usage over 10 runs: 131.21 MiB\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Convert the vectors to a NumPy array for statistical analysis"
      ],
      "metadata": {
        "id": "3Gxep-miEAVm"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Assuming vector_df has a column 'message_vector' with the vectors\n",
        "linformer_vectors = np.stack(linformer_vector_df['message_vector'].to_numpy())  # Stack the vectors into a 2D array"
      ],
      "metadata": {
        "id": "AInOx4hm7mR1"
      },
      "execution_count": 19,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# UMAP dimensionality check - scattered or clustered?"
      ],
      "metadata": {
        "id": "zZVCSpvsEJIq"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import umap.umap_ as umap  # Correct import statement for UMAP\n",
        "\n",
        "# Reduce dimensions using UMAP\n",
        "umap_reducer = umap.UMAP(n_components=2, random_state=42)\n",
        "umap_results = umap_reducer.fit_transform(linformer_vectors)\n",
        "\n",
        "# Plotting the results\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "plt.figure(figsize=(10, 8))\n",
        "plt.scatter(umap_results[:, 0], umap_results[:, 1], s=5)\n",
        "plt.title('UMAP Visualization of Vectors')\n",
        "plt.xlabel('UMAP component 1')\n",
        "plt.ylabel('UMAP component 2')\n",
        "plt.show()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 774
        },
        "id": "I55hh_VVm5Gs",
        "outputId": "26ff87cc-301f-4993-a06e-ce05f1c49560"
      },
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/umap/umap_.py:1945: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.\n",
            "  warn(f\"n_jobs value {self.n_jobs} overridden to 1 by setting random_state. Use no seed for parallelism.\")\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x800 with 1 Axes>"
            ],
            "image/png": "[encoded data, 52128 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Silhouette score via KMeans clustering"
      ],
      "metadata": {
        "id": "56wtMVhhEVzf"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.cluster import KMeans\n",
        "from sklearn.metrics import silhouette_score\n",
        "\n",
        "# Assuming we choose an arbitrary number of clusters, e.g., 5\n",
        "kmeans = KMeans(n_clusters=2, random_state=42)\n",
        "cluster_labels = kmeans.fit_predict(linformer_vectors)\n",
        "\n",
        "# Calculate the silhouette score\n",
        "sil_score = silhouette_score(linformer_vectors, cluster_labels)\n",
        "print(f\"Silhouette Score: {sil_score}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xGm3Fm5bnFae",
        "outputId": "85c1ccff-f959-468a-a1a4-277eba2e089f"
      },
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Silhouette Score: 0.7105976939201355\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Distribution of the Cosine similarity"
      ],
      "metadata": {
        "id": "8yhTWsSnEl30"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "from sklearn.metrics.pairwise import cosine_similarity\n",
        "\n",
        "# Assuming vector_df has a column 'message_vector' with the vectors\n",
        "vectors = np.stack(linformer_vector_df['message_vector'].to_numpy())  # Stack the vectors into a 2D array\n",
        "\n",
        "# Calculate the cosine similarity matrix\n",
        "cosine_sim_matrix = cosine_similarity(linformer_vectors)\n",
        "\n",
        "# Extract the upper triangle values from the cosine similarity matrix, excluding the diagonal\n",
        "upper_triangle_indices = np.triu_indices_from(cosine_sim_matrix, k=1)\n",
        "cosine_sim_values = cosine_sim_matrix[upper_triangle_indices]\n",
        "\n",
        "# Plotting the KDE of cosine similarities\n",
        "plt.figure(figsize=(10, 6))\n",
        "sns.kdeplot(cosine_sim_values, color='blue', fill=True)\n",
        "plt.title('KDE Plot of Cosine Similarities')\n",
        "plt.xlabel('Cosine Similarity')\n",
        "plt.ylabel('Density')\n",
        "plt.grid(True)\n",
        "plt.show()\n",
        "\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 564
        },
        "id": "NPbnuVKHqqtf",
        "outputId": "60c00803-a7f0-4843-c348-d3fa57db9388"
      },
      "execution_count": 22,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ],
            "image/png": "[encoded data, 37308 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Comparison model: LongFormer"
      ],
      "metadata": {
        "id": "FmwKV-BK-rKX"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# starts with the same data\n",
        "print(better_columns_df)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "l01czPQT-kSu",
        "outputId": "be7724d9-5632-41e9-e2dd-6e06430c843e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "shape: (1_027, 8)\n",
            "┌───────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┐\n",
            "│ index ┆ log.level  ┆ winlog.eve ┆ winlog.tas ┆ filtered_m ┆ image      ┆ target_fil ┆ text       │\n",
            "│ ---   ┆ ---        ┆ nt_id      ┆ k          ┆ essage     ┆ ---        ┆ ename      ┆ ---        │\n",
            "│ i64   ┆ str        ┆ ---        ┆ ---        ┆ ---        ┆ str        ┆ ---        ┆ str        │\n",
            "│       ┆            ┆ i64        ┆ str        ┆ str        ┆            ┆ str        ┆            │\n",
            "╞═══════╪════════════╪════════════╪════════════╪════════════╪════════════╪════════════╪════════════╡\n",
            "│ 0     ┆ informatio ┆ 10         ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆ accessed:  ┆ \\system32\\ ┆            ┆ accessed:  │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ svchost.ex ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆ -          ┆ e          ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ So…        ┆            ┆            ┆ So…        │\n",
            "│ 1     ┆ informatio ┆ 10         ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆ accessed:  ┆ \\system32\\ ┆            ┆ accessed:  │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ svchost.ex ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆ -          ┆ e          ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ So…        ┆            ┆            ┆ So…        │\n",
            "│ 2     ┆ informatio ┆ 1          ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ Create     ┆ Create:    ┆ \\servicing ┆            ┆ Create:    │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆ RuleName:  ┆ \\TrustedIn ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆ -          ┆ st…        ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ Proc…      ┆            ┆            ┆ Proc…      │\n",
            "│ 3     ┆ informatio ┆ 13         ┆ Registry   ┆ Registry   ┆ C:\\Windows ┆            ┆ Registry   │\n",
            "│       ┆ n          ┆            ┆ value set  ┆ value set: ┆ \\servicing ┆            ┆ value set: │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ \\TrustedIn ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ Regist…    ┆ Ta…        ┆ st…        ┆            ┆ Ta…        │\n",
            "│ …     ┆ …          ┆ …          ┆ …          ┆ …          ┆ …          ┆ …          ┆ …          │\n",
            "│ 1023  ┆ informatio ┆ 10         ┆ Process    ┆ Process    ┆ C:\\Program ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆ accessed:  ┆ Files (x86 ┆            ┆ accessed:  │\n",
            "│       ┆            ┆            ┆ (rule:     ┆ RuleName:  ┆ )\\Microsof ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆ -          ┆ t…         ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ So…        ┆            ┆            ┆ So…        │\n",
            "│ 1024  ┆ informatio ┆ 1          ┆ Process    ┆ Process    ┆ C:\\Windows ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ Create     ┆ Create:    ┆ \\System32\\ ┆            ┆ Create:    │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆ RuleName:  ┆ taskhostw. ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆ -          ┆ ex…        ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ Proc…      ┆            ┆            ┆ Proc…      │\n",
            "│ 1025  ┆ informatio ┆ 22         ┆ Dns query  ┆ Dns query: ┆            ┆            ┆ Dns query: │\n",
            "│       ┆ n          ┆            ┆ (rule:     ┆ RuleName:  ┆            ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ DnsQuery)  ┆ -          ┆            ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ ProcessId… ┆            ┆            ┆ ProcessId… │\n",
            "│ 1026  ┆ informatio ┆ 1          ┆ Process    ┆ Process    ┆ C:\\Program ┆            ┆ Process    │\n",
            "│       ┆ n          ┆            ┆ Create     ┆ Create:    ┆ Files\\RUXI ┆            ┆ Create:    │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆ RuleName:  ┆ M\\PLUGSche ┆            ┆ RuleName:  │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆ -          ┆ d…         ┆            ┆ -          │\n",
            "│       ┆            ┆            ┆            ┆ Proc…      ┆            ┆            ┆ Proc…      │\n",
            "└───────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┘\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Initialize and use LongFormer with the same pre-trained Tokenizer"
      ],
      "metadata": {
        "id": "J6REcr7hE1xz"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from tokenizers import Tokenizer\n",
        "import torch\n",
        "import numpy as np\n",
        "import polars as pl\n",
        "from transformers import LongformerModel\n",
        "\n",
        "# Load the custom tokenizer\n",
        "tokenizer = Tokenizer.from_file(\"log_tokenizer.json\")\n",
        "\n",
        "# Load LongFormer model\n",
        "model_name = 'allenai/longformer-base-4096'\n",
        "longformer_model = LongformerModel.from_pretrained(model_name)\n",
        "\n",
        "# Define the device (GPU if available, otherwise CPU)\n",
        "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
        "longformer_model.to(device)\n",
        "\n",
        "def vectorize_text(text):\n",
        "    MAX_LENGTH = 700  # Define the maximum length of tokens for the model\n",
        "\n",
        "    # Tokenize using the custom tokenizer\n",
        "    encoded = tokenizer.encode(text)\n",
        "\n",
        "    # Get token IDs\n",
        "    input_ids = encoded.ids\n",
        "\n",
        "    # Ensure the input_ids length is exactly MAX_LENGTH\n",
        "    if len(input_ids) > MAX_LENGTH:\n",
        "        input_ids = input_ids[:MAX_LENGTH]\n",
        "    else:\n",
        "        input_ids = input_ids + [0] * (MAX_LENGTH - len(input_ids))\n",
        "\n",
        "    # Convert to PyTorch tensor and move to the appropriate device\n",
        "    input_ids = torch.tensor([input_ids], dtype=torch.long).to(device)\n",
        "\n",
        "    # Create attention mask: 1 for non-padding, 0 for padding\n",
        "    attention_mask = (input_ids != 0).long()\n",
        "\n",
        "    # Get the model outputs, ensuring the input tensor is the correct size\n",
        "    with torch.no_grad():\n",
        "        outputs = longformer_model(input_ids, attention_mask=attention_mask)\n",
        "        vector = outputs.last_hidden_state.mean(dim=1).cpu().numpy()  # Average over the token embeddings\n",
        "    return vector.flatten()  # Flatten the array to 1D if needed\n",
        "\n",
        "# Assuming `better_columns_df` is your Polars DataFrame with a column \"filtered_message\"\n",
        "longformer_vector_df = better_columns_df.with_columns(\n",
        "    pl.col(\"filtered_message\").map_elements(vectorize_text, return_dtype=pl.Object).alias(\"message_vector\")\n",
        ")\n",
        "\n",
        "print(longformer_vector_df)\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000,
          "referenced_widgets": [
            "cf8262210b7c42bc8db80e1a102acf19",
            "509c0ac5a7624e2bb8618b978c8a80dc",
            "56c17b10c28c4fa9a6db05aa60a71f5e",
            "4b85c54d069e4a8d87520dbdad4c2c89",
            "6537feb3ffd24d2ea90b27a7a0a1aeb0",
            "4e2585503cca48f8a0428cc62d02e5f1",
            "b6ea52fd1054458e9458865f8f40ff84",
            "d70cc590fb28457b9ca7f74d8aa425f1",
            "a9116211ec3d407d9278f744d41507e6",
            "d706ec4068874b6eb52918afad80982e",
            "9c7b2917eb984de88aa6dbdec1bfa9cb",
            "c69abb9efb6b411fa4ee31b0c1910bae",
            "1170d27bc06e48bc985700e1703887b3",
            "6264397e6794478fa54e161f4434cc8b",
            "e5acc8060d7c4d25b6c13bb486eb5c39",
            "6ff11b9092db4dab98a68505955a612c",
            "b9f3902a7a844da0ab7d9bf5c2869db7",
            "86fa6d3c75e94c109ca0d44ddc7cb6e4",
            "4d7f1a3f6c044343a096951ed2a58603",
            "ef324ed1c14d4e9aac3312ed637f5789",
            "d19fd3e721b84b37b2f4da2bf03008de",
            "5d3d80342c864f419e64a323051e3509"
          ]
        },
        "id": "tpREQMax-yy3",
        "outputId": "fa3b4724-87ea-497c-fa6f-60f753b9088e"
      },
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n",
            "  warnings.warn(\n",
            "/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_token.py:89: UserWarning: \n",
            "The secret `HF_TOKEN` does not exist in your Colab secrets.\n",
            "To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.\n",
            "You will be able to reuse this secret in all of your notebooks.\n",
            "Please note that authentication is recommended but still optional to access public models or datasets.\n",
            "  warnings.warn(\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "config.json:   0%|          | 0.00/694 [00:00<?, ?B/s]"
            ],
            "application/vnd.jupyter.widget-view+json": {
              "version_major": 2,
              "version_minor": 0,
              "model_id": "cf8262210b7c42bc8db80e1a102acf19"
            }
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "pytorch_model.bin:   0%|          | 0.00/597M [00:00<?, ?B/s]"
            ],
            "application/vnd.jupyter.widget-view+json": {
              "version_major": 2,
              "version_minor": 0,
              "model_id": "c69abb9efb6b411fa4ee31b0c1910bae"
            }
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "Input ids are automatically padded from 700 to 1024 to be a multiple of `config.attention_window`: 512\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "shape: (1_027, 9)\n",
            "┌───────┬────────────┬────────────┬────────────┬───┬───────────┬───────────┬───────────┬───────────┐\n",
            "│ index ┆ log.level  ┆ winlog.eve ┆ winlog.tas ┆ … ┆ image     ┆ target_fi ┆ text      ┆ message_v │\n",
            "│ ---   ┆ ---        ┆ nt_id      ┆ k          ┆   ┆ ---       ┆ lename    ┆ ---       ┆ ector     │\n",
            "│ i64   ┆ str        ┆ ---        ┆ ---        ┆   ┆ str       ┆ ---       ┆ str       ┆ ---       │\n",
            "│       ┆            ┆ i64        ┆ str        ┆   ┆           ┆ str       ┆           ┆ object    │\n",
            "╞═══════╪════════════╪════════════╪════════════╪═══╪═══════════╪═══════════╪═══════════╪═══════════╡\n",
            "│ 0     ┆ informatio ┆ 10         ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [ 1.66481 │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆   ┆ s\\system3 ┆           ┆ accessed: ┆ 603e-02   │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ 2\\svchost ┆           ┆ RuleName: ┆ 5.9788990 │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆   ┆ .exe      ┆           ┆ -         ┆ 8e-03…    │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ So…       ┆           │\n",
            "│ 1     ┆ informatio ┆ 10         ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [ 2.54064 │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆   ┆ s\\system3 ┆           ┆ accessed: ┆ 687e-02   │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ 2\\svchost ┆           ┆ RuleName: ┆ 9.9657382 │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆   ┆ .exe      ┆           ┆ -         ┆ 8e-03…    │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ So…       ┆           │\n",
            "│ 2     ┆ informatio ┆ 1          ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [-2.47876 │\n",
            "│       ┆ n          ┆            ┆ Create     ┆   ┆ s\\servici ┆           ┆ Create:   ┆ 402e-02   │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆   ┆ ng\\Truste ┆           ┆ RuleName: ┆ 7.5210638 │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆   ┆ dInst…    ┆           ┆ -         ┆ 3e-02…    │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Proc…     ┆           │\n",
            "│ 3     ┆ informatio ┆ 13         ┆ Registry   ┆ … ┆ C:\\Window ┆           ┆ Registry  ┆ [-2.11402 │\n",
            "│       ┆ n          ┆            ┆ value set  ┆   ┆ s\\servici ┆           ┆ value     ┆ 588e-02   │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ ng\\Truste ┆           ┆ set:      ┆ 7.1680687 │\n",
            "│       ┆            ┆            ┆ Regist…    ┆   ┆ dInst…    ┆           ┆ RuleName: ┆ 4e-02…    │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Ta…       ┆           │\n",
            "│ …     ┆ …          ┆ …          ┆ …          ┆ … ┆ …         ┆ …         ┆ …         ┆ …         │\n",
            "│ 1023  ┆ informatio ┆ 10         ┆ Process    ┆ … ┆ C:\\Progra ┆           ┆ Process   ┆ [ 4.76494 │\n",
            "│       ┆ n          ┆            ┆ accessed   ┆   ┆ m Files   ┆           ┆ accessed: ┆ 990e-03   │\n",
            "│       ┆            ┆            ┆ (rule:     ┆   ┆ (x86)\\Mic ┆           ┆ RuleName: ┆ -3.913062 │\n",
            "│       ┆            ┆            ┆ ProcessA…  ┆   ┆ rosoft…   ┆           ┆ -         ┆ 44e-02…   │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ So…       ┆           │\n",
            "│ 1024  ┆ informatio ┆ 1          ┆ Process    ┆ … ┆ C:\\Window ┆           ┆ Process   ┆ [-2.70790 │\n",
            "│       ┆ n          ┆            ┆ Create     ┆   ┆ s\\System3 ┆           ┆ Create:   ┆ 458e-02   │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆   ┆ 2\\taskhos ┆           ┆ RuleName: ┆ 7.4740640 │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆   ┆ tw.ex…    ┆           ┆ -         ┆ 8e-02…    │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Proc…     ┆           │\n",
            "│ 1025  ┆ informatio ┆ 22         ┆ Dns query  ┆ … ┆           ┆           ┆ Dns       ┆ [-2.38244 │\n",
            "│       ┆ n          ┆            ┆ (rule:     ┆   ┆           ┆           ┆ query:    ┆ 906e-02   │\n",
            "│       ┆            ┆            ┆ DnsQuery)  ┆   ┆           ┆           ┆ RuleName: ┆ 7.2345621 │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ -         ┆ 9e-02…    │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ ProcessId ┆           │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ …         ┆           │\n",
            "│ 1026  ┆ informatio ┆ 1          ┆ Process    ┆ … ┆ C:\\Progra ┆           ┆ Process   ┆ [-1.94575 │\n",
            "│       ┆ n          ┆            ┆ Create     ┆   ┆ m Files\\R ┆           ┆ Create:   ┆ 228e-02   │\n",
            "│       ┆            ┆            ┆ (rule: Pro ┆   ┆ UXIM\\PLUG ┆           ┆ RuleName: ┆ 8.0403946 │\n",
            "│       ┆            ┆            ┆ cessCre…   ┆   ┆ Sched…    ┆           ┆ -         ┆ 3e-02…    │\n",
            "│       ┆            ┆            ┆            ┆   ┆           ┆           ┆ Proc…     ┆           │\n",
            "└───────┴────────────┴────────────┴────────────┴───┴───────────┴───────────┴───────────┴───────────┘\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install -q psutil\n",
        "\n",
        "import timeit\n",
        "import psutil\n",
        "import polars as pl\n",
        "import torch\n",
        "\n",
        "# Function to process the DataFrame and measure memory usage\n",
        "def process_and_measure(df):\n",
        "    # Reset GPU memory peak stats\n",
        "    if torch.cuda.is_available():\n",
        "        torch.cuda.reset_peak_memory_stats()\n",
        "\n",
        "    temp_df = df.with_columns(\n",
        "        pl.col(\"filtered_message\").map_elements(lambda x: vectorize_text(x).flatten(), return_dtype=pl.Object).alias(\"message_vector\")\n",
        "    )\n",
        "\n",
        "    # Get GPU memory usage\n",
        "    gpu_memory_usage = torch.cuda.max_memory_allocated() / (1024 ** 2) if torch.cuda.is_available() else 0\n",
        "    return gpu_memory_usage\n",
        "\n",
        "# Number of times to run the function\n",
        "n_runs = 10\n",
        "\n",
        "# Measure the runtime, CPU, and GPU memory usage over multiple runs\n",
        "runtimes = []\n",
        "cpu_memory_usages = []\n",
        "gpu_memory_usages = []\n",
        "\n",
        "for _ in range(n_runs):\n",
        "    # Record initial CPU memory usage\n",
        "    # psutil, because JAX doesn't work well with the memory_profiler\n",
        "    initial_memory = psutil.Process().memory_info().rss / (1024 ** 2)\n",
        "\n",
        "    # Measure runtime\n",
        "    runtime = timeit.timeit(lambda: process_and_measure(better_columns_df), number=1)\n",
        "    runtimes.append(runtime)\n",
        "\n",
        "    # Record final CPU memory usage\n",
        "    final_memory = psutil.Process().memory_info().rss / (1024 ** 2)\n",
        "    cpu_memory_usages.append(final_memory - initial_memory)\n",
        "\n",
        "    # Measure GPU memory usage\n",
        "    gpu_mem_usage = process_and_measure(better_columns_df)\n",
        "    gpu_memory_usages.append(gpu_mem_usage)\n",
        "\n",
        "# Calculate average runtime, CPU memory, and GPU memory usage\n",
        "average_runtime = np.mean(runtimes)\n",
        "average_cpu_memory_usage = np.mean(cpu_memory_usages)\n",
        "average_gpu_memory_usage = np.mean(gpu_memory_usages)\n",
        "\n",
        "print(f\"Average runtime over {n_runs} runs: {average_runtime:.6f} seconds\")\n",
        "print(f\"Average CPU memory usage over {n_runs} runs: {average_cpu_memory_usage:.2f} MiB\")\n",
        "print(f\"Average GPU memory usage over {n_runs} runs: {average_gpu_memory_usage:.2f} MiB\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "0IWHrarbUvJN",
        "outputId": "baf1b651-cd96-494a-aa01-f2c3f6e677c4"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Average runtime over 10 runs: 32.509051 seconds\n",
            "Average CPU memory usage over 10 runs: 0.00 MiB\n",
            "Average GPU memory usage over 10 runs: 739.78 MiB\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Assuming vector_df has a column 'message_vector' with the vectors\n",
        "longformer_vectors = np.stack(longformer_vector_df['message_vector'].to_numpy())  # Stack the vectors into a 2D array"
      ],
      "metadata": {
        "id": "LCnkFlrTB2qr"
      },
      "execution_count": 31,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import umap.umap_ as umap  # Correct import statement for UMAP\n",
        "\n",
        "# Reduce dimensions using UMAP\n",
        "umap_reducer = umap.UMAP(n_components=2, random_state=42)\n",
        "umap_results = umap_reducer.fit_transform(longformer_vectors)\n",
        "\n",
        "# Plotting the results\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "plt.figure(figsize=(10, 8))\n",
        "plt.scatter(umap_results[:, 0], umap_results[:, 1], s=5)\n",
        "plt.title('UMAP Visualization of Vectors')\n",
        "plt.xlabel('UMAP component 1')\n",
        "plt.ylabel('UMAP component 2')\n",
        "plt.show()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 754
        },
        "id": "I_O0HEDwAC9T",
        "outputId": "8e1647bb-bf3a-4831-acaa-d4031a8b14b1"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/umap/umap_.py:1945: UserWarning: n_jobs value 1 overridden to 1 by setting random_state. Use no seed for parallelism.\n",
            "  warn(f\"n_jobs value {self.n_jobs} overridden to 1 by setting random_state. Use no seed for parallelism.\")\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x800 with 1 Axes>"
            ],
            "image/png": "[encoded data, 37044 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.cluster import KMeans\n",
        "from sklearn.metrics import silhouette_score\n",
        "\n",
        "# Assuming we choose an arbitrary number of clusters, e.g., 5\n",
        "kmeans = KMeans(n_clusters=2, random_state=42)\n",
        "cluster_labels = kmeans.fit_predict(longformer_vectors)\n",
        "\n",
        "# Calculate the silhouette score\n",
        "sil_score = silhouette_score(longformer_vectors, cluster_labels)\n",
        "print(f\"Silhouette Score: {sil_score}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "w6hYJUe2APTt",
        "outputId": "0c923d0a-8b74-4e88-deec-f3c643039b86"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Silhouette Score: 0.7029939889907837\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "from sklearn.metrics.pairwise import cosine_similarity\n",
        "\n",
        "# Assuming vector_df has a column 'message_vector' with the vectors\n",
        "vectors = np.stack(longformer_vector_df['message_vector'].to_numpy())  # Stack the vectors into a 2D array\n",
        "\n",
        "# Calculate the cosine similarity matrix\n",
        "cosine_sim_matrix = cosine_similarity(longformer_vectors)\n",
        "\n",
        "# Extract the upper triangle values from the cosine similarity matrix, excluding the diagonal\n",
        "upper_triangle_indices = np.triu_indices_from(cosine_sim_matrix, k=1)\n",
        "cosine_sim_values = cosine_sim_matrix[upper_triangle_indices]\n",
        "\n",
        "# Plotting the KDE of cosine similarities\n",
        "plt.figure(figsize=(10, 6))\n",
        "sns.kdeplot(cosine_sim_values, color='blue', fill=True)\n",
        "plt.title('KDE Plot of Cosine Similarities')\n",
        "plt.xlabel('Cosine Similarity')\n",
        "plt.ylabel('Density')\n",
        "plt.grid(True)\n",
        "plt.show()\n",
        "\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 564
        },
        "id": "wz-3_DNDBe-L",
        "outputId": "486b54f0-101a-499d-d180-add867c012ae"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ],
            "image/png": "[encoded data, 36964 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "# Assuming `X` is the matrix of extracted features from your deep learning model\n",
        "# Replace this with your actual feature matrix\n",
        "X = linformer_vectors\n",
        "\n",
        "# Scale the features before applying PCA\n",
        "scaler = StandardScaler()\n",
        "X_scaled = scaler.fit_transform(X)\n",
        "\n",
        "# Apply PCA to retain 95% of the variance\n",
        "pca = PCA(n_components=0.95)\n",
        "X_pca = pca.fit_transform(X_scaled)\n",
        "\n",
        "# Output the results\n",
        "num_features_before = X.shape[1]\n",
        "num_features_after = X_pca.shape[1]\n",
        "explained_variance_ratio = pca.explained_variance_ratio_\n",
        "total_explained_variance = np.sum(explained_variance_ratio)\n",
        "\n",
        "print(\"For Standard Scaler\")\n",
        "print(f\"Number of features before PCA: {num_features_before}\")\n",
        "print(f\"Number of features after PCA: {num_features_after}\")\n",
        "print(f\"Explained variance ratio of each component: {explained_variance_ratio}\")\n",
        "print(f\"Total explained variance: {total_explained_variance}\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "pf6Ff46rJenw",
        "outputId": "652570a0-2de1-40c2-aaf5-a106d87ff2c2"
      },
      "execution_count": 23,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of features before PCA: 30000\n",
            "Number of features after PCA: 16\n",
            "Explained variance ratio of each component: [0.7322417  0.10258386 0.01919063 0.01368955 0.01286633 0.01047001\n",
            " 0.00869492 0.00842645 0.00745646 0.00658019 0.00584541 0.00514998\n",
            " 0.00491944 0.00477372 0.00384961 0.00355314]\n",
            "Total explained variance: 0.9502913951873779\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import RobustScaler\n",
        "\n",
        "# Assuming `X` is the matrix of extracted features from your deep learning model\n",
        "# Replace this with your actual feature matrix\n",
        "X = linformer_vectors\n",
        "\n",
        "# Scale the features before applying PCA\n",
        "scaler = RobustScaler()\n",
        "X_scaled = scaler.fit_transform(X)\n",
        "\n",
        "# Apply PCA to retain 95% of the variance\n",
        "pca = PCA(n_components=0.95)\n",
        "X_pca = pca.fit_transform(X_scaled)\n",
        "\n",
        "# Output the results\n",
        "num_features_before = X.shape[1]\n",
        "num_features_after = X_pca.shape[1]\n",
        "explained_variance_ratio = pca.explained_variance_ratio_\n",
        "total_explained_variance = np.sum(explained_variance_ratio)\n",
        "\n",
        "print(\"For Robust Scaler:\")\n",
        "print(f\"Number of features before PCA: {num_features_before}\")\n",
        "print(f\"Number of features after PCA: {num_features_after}\")\n",
        "print(f\"Explained variance ratio of each component: {explained_variance_ratio}\")\n",
        "print(f\"Total explained variance: {total_explained_variance}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "eK8wgP0IRPnr",
        "outputId": "8758e5dd-9616-4faf-9fd5-9e87c9625784"
      },
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "For Robust Scaler:\n",
            "Number of features before PCA: 30000\n",
            "Number of features after PCA: 12\n",
            "Explained variance ratio of each component: [0.780261   0.10317536 0.0133233  0.00962587 0.00900306 0.00735111\n",
            " 0.00611507 0.00592202 0.00531727 0.00460212 0.00413254 0.00365149]\n",
            "Total explained variance: 0.952480137348175\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from sklearn.preprocessing import QuantileTransformer\n",
        "from sklearn.decomposition import PCA\n",
        "import numpy as np\n",
        "\n",
        "# Assuming X is your feature matrix\n",
        "X = linformer_vectors\n",
        "\n",
        "# Initialize and fit QuantileTransformer\n",
        "qt = QuantileTransformer(n_quantiles=1000, output_distribution='normal')\n",
        "X_scaled = qt.fit_transform(X)\n",
        "\n",
        "# Apply PCA\n",
        "pca = PCA(n_components=0.95)\n",
        "X_pca = pca.fit_transform(X_scaled)\n",
        "\n",
        "# Output results\n",
        "num_features_before = X.shape[1]\n",
        "num_features_after = X_pca.shape[1]\n",
        "explained_variance_ratio = pca.explained_variance_ratio_\n",
        "total_explained_variance = np.sum(explained_variance_ratio)\n",
        "\n",
        "print(\"For QuantileTransformer:\")\n",
        "print(f\"Number of features before PCA: {num_features_before}\")\n",
        "print(f\"Number of features after PCA: {num_features_after}\")\n",
        "print(f\"Explained variance ratio of each component: {explained_variance_ratio}\")\n",
        "print(f\"Total explained variance: {total_explained_variance}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "GNpC0dqQR0c1",
        "outputId": "ecfdbd8a-f243-4d20-b52f-f71e2d88f372"
      },
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "For QuantileTransformer:\n",
            "Number of features before PCA: 30000\n",
            "Number of features after PCA: 44\n",
            "Explained variance ratio of each component: [0.5520516  0.06681303 0.03466679 0.02603397 0.02438432 0.01991471\n",
            " 0.01807965 0.01676909 0.01452703 0.01407685 0.01204457 0.01079712\n",
            " 0.01011274 0.00953582 0.00818911 0.00781149 0.00750947 0.00684127\n",
            " 0.00666759 0.00635126 0.0060087  0.00576267 0.00530005 0.00508402\n",
            " 0.0044879  0.00436854 0.00426688 0.0040915  0.00363791 0.00351764\n",
            " 0.00315828 0.00294013 0.00270898 0.00254636 0.0024569  0.00226332\n",
            " 0.0022466  0.00212357 0.00194851 0.00179851 0.0016702  0.00165001\n",
            " 0.00159225 0.00152319]\n",
            "Total explained variance: 0.9503300786018372\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "# Assuming `X` is the matrix of extracted features from your deep learning model\n",
        "# Replace this with your actual feature matrix\n",
        "X = longformer_vectors\n",
        "\n",
        "# Scale the features before applying PCA\n",
        "scaler = StandardScaler()\n",
        "X_scaled = scaler.fit_transform(X)\n",
        "\n",
        "# Apply PCA to retain 95% of the variance\n",
        "pca = PCA(n_components=0.95)\n",
        "X_pca = pca.fit_transform(X_scaled)\n",
        "\n",
        "# Output the results\n",
        "num_features_before = X.shape[1]\n",
        "num_features_after = X_pca.shape[1]\n",
        "explained_variance_ratio = pca.explained_variance_ratio_\n",
        "total_explained_variance = np.sum(explained_variance_ratio)\n",
        "\n",
        "print(f\"Number of features before PCA: {num_features_before}\")\n",
        "print(f\"Number of features after PCA: {num_features_after}\")\n",
        "print(f\"Explained variance ratio of each component: {explained_variance_ratio}\")\n",
        "print(f\"Total explained variance: {total_explained_variance}\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "TeaiZpy_H67h",
        "outputId": "91fb9f4c-6c74-4511-9f22-9ce8192bf948"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of features before PCA: 768\n",
            "Number of features after PCA: 12\n",
            "Explained variance ratio of each component: [0.61036086 0.20625743 0.0349943  0.02877296 0.01811446 0.01343036\n",
            " 0.01034578 0.00865575 0.00768904 0.0061328  0.00457506 0.00375366]\n",
            "Total explained variance: 0.9530825018882751\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "import numpy as np\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "# X is the features matrix\n",
        "x = linformer_vectors\n",
        "\n",
        "\n",
        "# Standardize the features\n",
        "scaler = StandardScaler()\n",
        "X_scaled = scaler.fit_transform(X)\n",
        "\n",
        "# Apply PCA\n",
        "pca = PCA(n_components=0.95)\n",
        "X_pca = pca.fit_transform(X_scaled)\n",
        "explained_variance_ratio = pca.explained_variance_ratio_\n",
        "cumulative_variance = np.cumsum(explained_variance_ratio)\n",
        "\n",
        "# Plotting the Scree plot\n",
        "plt.figure(figsize=(10, 4))\n",
        "plt.bar(range(1, len(explained_variance_ratio) + 1), explained_variance_ratio, alpha=0.6, color='g', label='Individual explained variance')\n",
        "plt.ylabel('Explained variance ratio')\n",
        "plt.xlabel('Principal components')\n",
        "plt.title('Scree Plot')\n",
        "plt.legend(loc='best')\n",
        "plt.tight_layout()\n",
        "\n",
        "# Plotting the Cumulative Variance plot\n",
        "plt.figure(figsize=(10, 4))\n",
        "plt.plot(range(1, len(cumulative_variance) + 1), cumulative_variance, marker='o', linestyle='-', color='b', label='Cumulative explained variance')\n",
        "plt.xlabel('Number of components')\n",
        "plt.ylabel('Cumulative explained variance')\n",
        "plt.title('Cumulative Variance Plot')\n",
        "plt.axhline(y=0.95, color='r', linestyle='--', label='95% Explained Variance')\n",
        "plt.legend(loc='best')\n",
        "plt.tight_layout()\n",
        "\n",
        "# Displaying the plots\n",
        "plt.show()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 797
        },
        "id": "qOa9OTV6DpOK",
        "outputId": "cfede8d1-e334-426f-c517-186035938323"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x400 with 1 Axes>"
            ],
            "image/png": "[encoded data, 26976 characters]\n"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x400 with 1 Axes>"
            ],
            "image/png": "[encoded data, 47628 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "import numpy as np\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "# X is the features matrix\n",
        "x = longformer_vectors\n",
        "\n",
        "\n",
        "# Standardize the features\n",
        "scaler = StandardScaler()\n",
        "X_scaled = scaler.fit_transform(X)\n",
        "\n",
        "# Apply PCA\n",
        "pca = PCA(n_components=0.95)\n",
        "X_pca = pca.fit_transform(X_scaled)\n",
        "explained_variance_ratio = pca.explained_variance_ratio_\n",
        "cumulative_variance = np.cumsum(explained_variance_ratio)\n",
        "\n",
        "# Plotting the Scree plot\n",
        "plt.figure(figsize=(10, 4))\n",
        "plt.bar(range(1, len(explained_variance_ratio) + 1), explained_variance_ratio, alpha=0.6, color='g', label='Individual explained variance')\n",
        "plt.ylabel('Explained variance ratio')\n",
        "plt.xlabel('Principal components')\n",
        "plt.title('Scree Plot')\n",
        "plt.legend(loc='best')\n",
        "plt.tight_layout()\n",
        "\n",
        "# Plotting the Cumulative Variance plot\n",
        "plt.figure(figsize=(10, 4))\n",
        "plt.plot(range(1, len(cumulative_variance) + 1), cumulative_variance, marker='o', linestyle='-', color='b', label='Cumulative explained variance')\n",
        "plt.xlabel('Number of components')\n",
        "plt.ylabel('Cumulative explained variance')\n",
        "plt.title('Cumulative Variance Plot')\n",
        "plt.axhline(y=0.95, color='r', linestyle='--', label='95% Explained Variance')\n",
        "plt.legend(loc='best')\n",
        "plt.tight_layout()\n",
        "\n",
        "# Displaying the plots\n",
        "plt.show()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 797
        },
        "id": "KYRsJBkkD7ep",
        "outputId": "0169dcbe-d0e5-48a8-bcce-471d83ff095c"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x400 with 1 Axes>"
            ],
            "image/png": "[encoded data, 26976 characters]\n"
          },
          "metadata": {}
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x400 with 1 Axes>"
            ],
            "image/png": "[encoded data, 47628 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import StandardScaler\n",
        "\n",
        "\n",
        "X_1 = longformer_vectors\n",
        "X_2 = linformer_vectors\n",
        "\n",
        "# Standardize the features independently\n",
        "scaler1 = StandardScaler()\n",
        "X_1_scaled = scaler1.fit_transform(X_1)\n",
        "\n",
        "scaler2 = StandardScaler()\n",
        "X_2_scaled = scaler2.fit_transform(X_2)\n",
        "\n",
        "# Apply PCA\n",
        "pca = PCA(n_components=2)  # Reducing to 2 components for a 2D plot\n",
        "X_1_pca = pca.fit_transform(X_1_scaled)\n",
        "pca2 = PCA(n_components=2)\n",
        "X_2_pca = pca2.fit_transform(X_2_scaled)\n",
        "\n",
        "# Plotting\n",
        "plt.figure(figsize=(10, 6))\n",
        "plt.scatter(X_1_pca[:, 0], X_1_pca[:, 1], color='blue', alpha=0.5, label='Longformer Model')\n",
        "plt.scatter(X_2_pca[:, 0], X_2_pca[:, 1], color='red', alpha=0.5, label='Linformer Model')\n",
        "plt.xlabel('Principal Component 1')\n",
        "plt.ylabel('Principal Component 2')\n",
        "plt.title('PCA Comparison of Two Models')\n",
        "plt.legend()\n",
        "plt.grid(True)\n",
        "plt.show()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 564
        },
        "id": "6X6EyalGEe4B",
        "outputId": "568c07f4-cea8-40ff-c4ae-1a1d1039120c"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ],
            "image/png": "[encoded data, 74872 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "from sklearn.metrics.pairwise import cosine_similarity\n",
        "\n",
        "# Assuming longformer_vector_df and linformer_vector_df have a column 'message_vector' with the vectors\n",
        "# Stacking vectors into a 2D array for each model\n",
        "longformer_vectors = np.stack(longformer_vector_df['message_vector'].to_numpy())\n",
        "linformer_vectors = np.stack(linformer_vector_df['message_vector'].to_numpy())\n",
        "\n",
        "# Calculate the cosine similarity matrix for each model\n",
        "cosine_sim_matrix_long = cosine_similarity(longformer_vectors)\n",
        "cosine_sim_matrix_lin = cosine_similarity(linformer_vectors)\n",
        "\n",
        "# Extract the upper triangle values from each cosine similarity matrix, excluding the diagonal\n",
        "upper_triangle_indices_long = np.triu_indices_from(cosine_sim_matrix_long, k=1)\n",
        "cosine_sim_values_long = cosine_sim_matrix_long[upper_triangle_indices_long]\n",
        "\n",
        "upper_triangle_indices_lin = np.triu_indices_from(cosine_sim_matrix_lin, k=1)\n",
        "cosine_sim_values_lin = cosine_sim_matrix_lin[upper_triangle_indices_lin]\n",
        "\n",
        "# Plotting the KDE of cosine similarities for both models\n",
        "plt.figure(figsize=(12, 6))\n",
        "sns.kdeplot(cosine_sim_values_long, color='blue', fill=True, label='Longformer Model')\n",
        "sns.kdeplot(cosine_sim_values_lin, color='green', fill=True, label='Linformer Model')\n",
        "plt.title('Comparison of Cosine Similarity Distributions')\n",
        "plt.xlabel('Cosine Similarity')\n",
        "plt.ylabel('Density')\n",
        "plt.grid(True)\n",
        "plt.legend()\n",
        "plt.show()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 564
        },
        "id": "hosMIGN4E5Vj",
        "outputId": "2f481f84-219b-4289-866f-4e81b04d9db8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 1200x600 with 1 Axes>"
            ],
            "image/png": "[encoded data, 51148 characters]\n"
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Approaching Quantile Transoformer for feature scaling for LinFormer model vectors"
      ],
      "metadata": {
        "id": "SxhOQqiHhPju"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "import numpy as np\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import StandardScaler, QuantileTransformer\n",
        "\n",
        "# Assuming X is your feature matrix\n",
        "X = linformer_vectors\n",
        "\n",
        "def process_and_pca(X, scaler):\n",
        "    X_scaled = scaler.fit_transform(X)\n",
        "    pca = PCA(n_components=0.95)\n",
        "    X_pca = pca.fit_transform(X_scaled)\n",
        "    explained_variance_ratio = pca.explained_variance_ratio_\n",
        "    cumulative_variance = np.cumsum(explained_variance_ratio)\n",
        "    return explained_variance_ratio, cumulative_variance\n",
        "\n",
        "# Process for StandardScaler\n",
        "explained_variance_ratio_std, cumulative_variance_std = process_and_pca(X, StandardScaler())\n",
        "\n",
        "# Process for QuantileTransformer\n",
        "explained_variance_ratio_qt, cumulative_variance_qt = process_and_pca(X, QuantileTransformer(n_quantiles=1000, output_distribution='normal'))\n",
        "\n",
        "# Create subplots\n",
        "fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 12))\n",
        "\n",
        "# Scree plot StandardScaler\n",
        "axes[0, 0].bar(range(1, len(explained_variance_ratio_std) + 1), explained_variance_ratio_std, alpha=0.6, color='g', label='StandardScaler: Individual explained variance')\n",
        "axes[0, 0].set_title('StandardScaler Scree Plot')\n",
        "axes[0, 0].set_xlabel('Principal components')\n",
        "axes[0, 0].set_ylabel('Explained variance ratio')\n",
        "axes[0, 0].legend()\n",
        "\n",
        "# Cumulative Variance plot StandardScaler\n",
        "axes[1, 0].plot(range(1, len(cumulative_variance_std) + 1), cumulative_variance_std, marker='o', linestyle='-', color='b', label='StandardScaler: Cumulative explained variance')\n",
        "axes[1, 0].axhline(y=0.95, color='r', linestyle='--', label='95% Explained Variance')\n",
        "axes[1, 0].set_title('StandardScaler Cumulative Variance Plot')\n",
        "axes[1, 0].set_xlabel('Number of components')\n",
        "axes[1, 0].set_ylabel('Cumulative explained variance')\n",
        "axes[1, 0].legend()\n",
        "\n",
        "# Scree plot QuantileTransformer\n",
        "axes[0, 1].bar(range(1, len(explained_variance_ratio_qt) + 1), explained_variance_ratio_qt, alpha=0.6, color='g', label='QuantileTransformer: Individual explained variance')\n",
        "axes[0, 1].set_title('QuantileTransformer Scree Plot')\n",
        "axes[0, 1].set_xlabel('Principal components')\n",
        "axes[0, 1].set_ylabel('Explained variance ratio')\n",
        "axes[0, 1].legend()\n",
        "\n",
        "# Cumulative Variance plot QuantileTransformer\n",
        "axes[1, 1].plot(range(1, len(cumulative_variance_qt) + 1), cumulative_variance_qt, marker='o', linestyle='-', color='b', label='QuantileTransformer: Cumulative explained variance')\n",
        "axes[1, 1].axhline(y=0.95, color='r', linestyle='--', label='95% Explained Variance')\n",
        "axes[1, 1].set_title('QuantileTransformer Cumulative Variance Plot')\n",
        "axes[1, 1].set_xlabel('Number of components')\n",
        "axes[1, 1].set_ylabel('Cumulative explained variance')\n",
        "axes[1, 1].legend()\n",
        "\n",
        "# Adjust layout and display the plots\n",
        "plt.tight_layout()\n",
        "plt.show()\n",
        "\n",
        "# Print the number of components needed to explain 95% of the variance\n",
        "n_components_std = np.argmax(cumulative_variance_std >= 0.95) + 1\n",
        "n_components_qt = np.argmax(cumulative_variance_qt >= 0.95) + 1\n",
        "\n",
        "print(f\"Number of components needed to explain 95% of variance (StandardScaler): {n_components_std}\")\n",
        "print(f\"Number of components needed to explain 95% of variance (QuantileTransformer): {n_components_qt}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "-n1_yRcaGYZD",
        "outputId": "0a4bff53-25a4-4ca1-8030-7ee5d94ccb50"
      },
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 2000x1200 with 4 Axes>"
            ],
            "image/png": "[encoded data, 154412 characters]\n"
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of components needed to explain 95% of variance (StandardScaler): 16\n",
            "Number of components needed to explain 95% of variance (QuantileTransformer): 44\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Quantile Transformer vs. Standard Scaler for feature scaling"
      ],
      "metadata": {
        "id": "kgdy9N8lhEaF"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import seaborn as sns\n",
        "import numpy as np\n",
        "from sklearn.decomposition import PCA\n",
        "from sklearn.preprocessing import StandardScaler, QuantileTransformer\n",
        "\n",
        "# Assuming X is your feature matrix\n",
        "X = linformer_vectors\n",
        "\n",
        "# Process and plot for StandardScaler\n",
        "scaler_std = StandardScaler()\n",
        "X_scaled_std = scaler_std.fit_transform(X)\n",
        "pca_std = PCA(n_components=0.95)\n",
        "X_pca_std = pca_std.fit_transform(X_scaled_std)\n",
        "explained_variance_ratio_std = pca_std.explained_variance_ratio_\n",
        "cumulative_variance_std = np.cumsum(explained_variance_ratio_std)\n",
        "\n",
        "# Process and plot for QuantileTransformer\n",
        "scaler_qt = QuantileTransformer(n_quantiles=1000, output_distribution='normal')\n",
        "X_scaled_qt = scaler_qt.fit_transform(X)\n",
        "pca_qt = PCA(n_components=0.95)\n",
        "X_pca_qt = pca_qt.fit_transform(X_scaled_qt)\n",
        "explained_variance_ratio_qt = pca_qt.explained_variance_ratio_\n",
        "cumulative_variance_qt = np.cumsum(explained_variance_ratio_qt)\n",
        "\n",
        "# Create subplots\n",
        "fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 12))\n",
        "\n",
        "# Scree plot StandardScaler\n",
        "axes[0, 0].bar(range(1, len(explained_variance_ratio_std) + 1), explained_variance_ratio_std, alpha=0.6, color='g', label='StandardScaler: Individual explained variance')\n",
        "axes[0, 0].set_title('StandardScaler Scree Plot')\n",
        "axes[0, 0].set_xlabel('Principal components')\n",
        "axes[0, 0].set_ylabel('Explained variance ratio')\n",
        "axes[0, 0].legend()\n",
        "\n",
        "# Cumulative Variance plot StandardScaler\n",
        "axes[1, 0].plot(range(1, len(cumulative_variance_std) + 1), cumulative_variance_std, marker='o', linestyle='-', color='b', label='StandardScaler: Cumulative explained variance')\n",
        "axes[1, 0].axhline(y=0.95, color='r', linestyle='--', label='95% Explained Variance')\n",
        "axes[1, 0].set_title('StandardScaler Cumulative Variance Plot')\n",
        "axes[1, 0].set_xlabel('Number of components')\n",
        "axes[1, 0].set_ylabel('Cumulative explained variance')\n",
        "axes[1, 0].legend()\n",
        "\n",
        "# Scree plot QuantileTransformer\n",
        "axes[0, 1].bar(range(1, len(explained_variance_ratio_qt) + 1), explained_variance_ratio_qt, alpha=0.6, color='g', label='QuantileTransformer: Individual explained variance')\n",
        "axes[0, 1].set_title('QuantileTransformer Scree Plot')\n",
        "axes[0, 1].set_xlabel('Principal components')\n",
        "axes[0, 1].set_ylabel('Explained variance ratio')\n",
        "axes[0, 1].legend()\n",
        "\n",
        "# Cumulative Variance plot QuantileTransformer\n",
        "axes[1, 1].plot(range(1, len(cumulative_variance_qt) + 1), cumulative_variance_qt, marker='o', linestyle='-', color='b', label='QuantileTransformer: Cumulative explained variance')\n",
        "axes[1, 1].axhline(y=0.95, color='r', linestyle='--', label='95% Explained Variance')\n",
        "axes[1, 1].set_title('QuantileTransformer Cumulative Variance Plot')\n",
        "axes[1, 1].set_xlabel('Number of components')\n",
        "axes[1, 1].set_ylabel('Cumulative explained variance')\n",
        "axes[1, 1].legend()\n",
        "\n",
        "# Adjust layout and display the plots\n",
        "plt.tight_layout()\n",
        "plt.show()\n",
        "\n",
        "# Print the number of components needed to explain 95% of the variance\n",
        "n_components_std = np.argmax(cumulative_variance_std >= 0.95) + 1\n",
        "n_components_qt = np.argmax(cumulative_variance_qt >= 0.95) + 1\n",
        "\n",
        "print(f\"Number of components needed to explain 95% of variance (StandardScaler): {n_components_std}\")\n",
        "print(f\"Number of components needed to explain 95% of variance (QuantileTransformer): {n_components_qt}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 702
        },
        "id": "dVlcnu0YSiIT",
        "outputId": "26e305a3-a0fe-44d2-886c-fa49b8afc4de"
      },
      "execution_count": 28,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<Figure size 2000x1200 with 4 Axes>"
            ],
            "image/png": "[encoded data, 154412 characters]\n"
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of components needed to explain 95% of variance (StandardScaler): 16\n",
            "Number of components needed to explain 95% of variance (QuantileTransformer): 44\n"
          ]
        }
      ]
    }
  ]
}