{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\n# Use the kagglehub client library to attach Kaggle resources like competitions, datasets, and models to your session\n# Learn more about kagglehub: https://github.com/Kaggle/kagglehub/blob/main/README.md\n\nimport kagglehub\n# kagglehub.dataset_download('<owner>/<dataset-slug>')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import kagglehub\n\n# Download latest version\npath = kagglehub.dataset_download(\"prayashdas/autistic-children-facial-image-dataset\")\n\nprint(\"Path to dataset files:\", path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:09:36.841916Z","iopub.execute_input":"2026-09-24T09:09:36.842195Z","iopub.status.idle":"2026-09-24T09:10:30.023198Z","shell.execute_reply.started":"2026-09-24T09:09:36.842168Z","shell.execute_reply":"2026-09-24T09:10:30.022193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install -q --upgrade kaggle","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:38:02.187686Z","iopub.execute_input":"2026-09-24T09:38:02.188347Z","iopub.status.idle":"2026-09-24T09:38:08.804303Z","shell.execute_reply.started":"2026-09-24T09:38:02.188314Z","shell.execute_reply":"2026-09-24T09:38:08.803488Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!kaggle competitions files -c abide","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:38:35.935354Z","iopub.execute_input":"2026-09-24T09:38:35.935699Z","iopub.status.idle":"2026-09-24T09:38:36.975989Z","shell.execute_reply.started":"2026-09-24T09:38:35.935666Z","shell.execute_reply":"2026-09-24T09:38:36.974947Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nfor root, dirs, files in os.walk(\"/kaggle/input\"):\n    for file in files:\n        if \"pheno\" in file.lower():\n            print(os.path.join(root, file))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:46:58.954609Z","iopub.execute_input":"2026-09-24T09:46:58.955595Z","iopub.status.idle":"2026-09-24T09:47:41.071141Z","shell.execute_reply.started":"2026-09-24T09:46:58.955552Z","shell.execute_reply":"2026-09-24T09:47:41.070042Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nprint(\"Kaggle input folders/files:\")\n\nfor root, dirs, files in os.walk(\"/kaggle/input\"):\n    for file in files:\n        if \"pheno\" in file.lower():\n            print(os.path.join(root, file))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:49:04.134877Z","iopub.execute_input":"2026-09-24T09:49:04.135736Z","iopub.status.idle":"2026-09-24T09:49:17.991972Z","shell.execute_reply.started":"2026-09-24T09:49:04.135681Z","shell.execute_reply":"2026-09-24T09:49:17.991144Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\npath = \"/kaggle/input/competitions/abide/comp_data/pheno_train.csv\"\n\ndf = pd.read_csv(path)\n\nprint(\"Dataset Shape:\", df.shape)\n\nprint(\"\\nColumn Names:\")\nfor i, col in enumerate(df.columns):\n    print(i, \":\", col)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:50:03.757976Z","iopub.execute_input":"2026-09-24T09:50:03.758965Z","iopub.status.idle":"2026-09-24T09:50:03.81002Z","shell.execute_reply.started":"2026-09-24T09:50:03.758931Z","shell.execute_reply":"2026-09-24T09:50:03.808852Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"iq_cols = [\n    col for col in df.columns\n    if any(x in col.lower() for x in [\"iq\", \"fiq\", \"viq\", \"piq\"])\n]\n\nprint(\"\\nIQ-related columns:\")\nprint(iq_cols)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:50:30.677534Z","iopub.execute_input":"2026-09-24T09:50:30.67799Z","iopub.status.idle":"2026-09-24T09:50:30.684558Z","shell.execute_reply.started":"2026-09-24T09:50:30.677956Z","shell.execute_reply":"2026-09-24T09:50:30.683475Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(df[\"AGE_AT_SCAN\"].describe())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:52:30.826972Z","iopub.execute_input":"2026-09-24T09:52:30.827317Z","iopub.status.idle":"2026-09-24T09:52:30.847947Z","shell.execute_reply.started":"2026-09-24T09:52:30.827283Z","shell.execute_reply":"2026-09-24T09:52:30.846939Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Minimum age:\", df[\"AGE_AT_SCAN\"].min())\nprint(\"Maximum age:\", df[\"AGE_AT_SCAN\"].max())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:52:39.178994Z","iopub.execute_input":"2026-09-24T09:52:39.179355Z","iopub.status.idle":"2026-09-24T09:52:39.185352Z","shell.execute_reply.started":"2026-09-24T09:52:39.179327Z","shell.execute_reply":"2026-09-24T09:52:39.184418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nchild_df = df[df[\"AGE_AT_SCAN\"] <= 18].copy()\n\nprint(\"Child dataset shape:\", child_df.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:53:01.577481Z","iopub.execute_input":"2026-09-24T09:53:01.57823Z","iopub.status.idle":"2026-09-24T09:53:01.587754Z","shell.execute_reply.started":"2026-09-24T09:53:01.578195Z","shell.execute_reply":"2026-09-24T09:53:01.586956Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(child_df[\"DX_GROUP\"].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:53:13.010564Z","iopub.execute_input":"2026-09-24T09:53:13.010947Z","iopub.status.idle":"2026-09-24T09:53:13.022047Z","shell.execute_reply.started":"2026-09-24T09:53:13.010915Z","shell.execute_reply":"2026-09-24T09:53:13.02109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"iq_cols = [\"FIQ\", \"VIQ\", \"PIQ\"]\n\nprint(child_df[iq_cols].isnull().sum())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:53:27.050771Z","iopub.execute_input":"2026-09-24T09:53:27.051468Z","iopub.status.idle":"2026-09-24T09:53:27.059289Z","shell.execute_reply.started":"2026-09-24T09:53:27.051434Z","shell.execute_reply":"2026-09-24T09:53:27.058285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\n    child_df[iq_cols].isnull().mean() * 100\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:53:35.940448Z","iopub.execute_input":"2026-09-24T09:53:35.941301Z","iopub.status.idle":"2026-09-24T09:53:35.948521Z","shell.execute_reply.started":"2026-09-24T09:53:35.94127Z","shell.execute_reply":"2026-09-24T09:53:35.947476Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_iq = child_df[\n    [\"SUB_ID\", \"AGE_AT_SCAN\", \"SEX\",\n     \"FIQ\", \"VIQ\", \"PIQ\", \"DX_GROUP\"]\n].copy()\n\nprint(final_iq.shape)\nprint(final_iq.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:53:51.095833Z","iopub.execute_input":"2026-09-24T09:53:51.096185Z","iopub.status.idle":"2026-09-24T09:53:51.112053Z","shell.execute_reply.started":"2026-09-24T09:53:51.09616Z","shell.execute_reply":"2026-09-24T09:53:51.111107Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(df[\"AGE_AT_SCAN\"].describe())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:54:05.298594Z","iopub.execute_input":"2026-09-24T09:54:05.298917Z","iopub.status.idle":"2026-09-24T09:54:05.307737Z","shell.execute_reply.started":"2026-09-24T09:54:05.298891Z","shell.execute_reply":"2026-09-24T09:54:05.306768Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"child_df = df[df[\"AGE_AT_SCAN\"] <= 18].copy()\nprint(\"Child dataset shape:\", child_df.shape)\nprint(child_df[\"DX_GROUP\"].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:54:14.415695Z","iopub.execute_input":"2026-09-24T09:54:14.416379Z","iopub.status.idle":"2026-09-24T09:54:14.425131Z","shell.execute_reply.started":"2026-09-24T09:54:14.41635Z","shell.execute_reply":"2026-09-24T09:54:14.424009Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"iq_cols = [\"FIQ\", \"VIQ\", \"PIQ\"]\nprint(child_df[iq_cols].isnull().sum())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:54:21.449443Z","iopub.execute_input":"2026-09-24T09:54:21.450378Z","iopub.status.idle":"2026-09-24T09:54:21.457534Z","shell.execute_reply.started":"2026-09-24T09:54:21.450321Z","shell.execute_reply":"2026-09-24T09:54:21.456771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(child_df[iq_cols].describe())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:54:29.425416Z","iopub.execute_input":"2026-09-24T09:54:29.425737Z","iopub.status.idle":"2026-09-24T09:54:29.442579Z","shell.execute_reply.started":"2026-09-24T09:54:29.425695Z","shell.execute_reply":"2026-09-24T09:54:29.441635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"iq_cols = [\"FIQ\", \"VIQ\", \"PIQ\"]\n\niq_clean = child_df.dropna(\n    subset=iq_cols\n).copy()\n\nprint(\"Original child records:\", len(child_df))\nprint(\"Complete IQ records:\", len(iq_clean))\n\nprint(\"\\nClass distribution:\")\nprint(iq_clean[\"DX_GROUP\"].value_counts())\n\nprint(\"\\nMissing values:\")\nprint(iq_clean[iq_cols].isnull().sum())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:56:14.871696Z","iopub.execute_input":"2026-09-24T09:56:14.872453Z","iopub.status.idle":"2026-09-24T09:56:14.884644Z","shell.execute_reply.started":"2026-09-24T09:56:14.872416Z","shell.execute_reply":"2026-09-24T09:56:14.883809Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(iq_clean[iq_cols].describe())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:58:08.10663Z","iopub.execute_input":"2026-09-24T09:58:08.106989Z","iopub.status.idle":"2026-09-24T09:58:08.12356Z","shell.execute_reply.started":"2026-09-24T09:58:08.106962Z","shell.execute_reply":"2026-09-24T09:58:08.122666Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_iq = iq_clean[\n    [\n        \"SUB_ID\",\n        \"AGE_AT_SCAN\",\n        \"SEX\",\n        \"FIQ\",\n        \"VIQ\",\n        \"PIQ\",\n        \"DX_GROUP\"\n    ]\n].copy()\n\nprint(\"Final IQ dataset shape:\", final_iq.shape)\n\nprint(\"\\nFirst 10 records:\")\nprint(final_iq.head(10))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:58:20.635366Z","iopub.execute_input":"2026-09-24T09:58:20.636203Z","iopub.status.idle":"2026-09-24T09:58:20.64688Z","shell.execute_reply.started":"2026-09-24T09:58:20.636167Z","shell.execute_reply":"2026-09-24T09:58:20.646062Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_iq[\"LABEL\"] = final_iq[\"DX_GROUP\"].map({\n    1: 1,   # ASD\n    2: 0    # Non-ASD\n})\n\nprint(final_iq[\"LABEL\"].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T09:58:33.441901Z","iopub.execute_input":"2026-09-24T09:58:33.442241Z","iopub.status.idle":"2026-09-24T09:58:33.452335Z","shell.execute_reply.started":"2026-09-24T09:58:33.442209Z","shell.execute_reply":"2026-09-24T09:58:33.451364Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nprint(\"========== DATASET INSPECTION ==========\\n\")\n\nfor root, dirs, files in os.walk(\"/kaggle/input\"):\n\n    image_files = [\n        f for f in files\n        if f.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\", \".bmp\", \".webp\")\n        )\n    ]\n\n    if image_files:\n        print(\"Folder :\", root)\n        print(\"Images :\", len(image_files))\n        print(\"Sample :\", image_files[:5])\n        print(\"-\" * 60)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:12:08.282638Z","iopub.execute_input":"2026-09-24T10:12:08.283049Z","iopub.status.idle":"2026-09-24T10:12:28.499649Z","shell.execute_reply.started":"2026-09-24T10:12:08.283023Z","shell.execute_reply":"2026-09-24T10:12:28.498827Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nclasses = [\"autistic\", \"non_autistic\"]\n\nprint(\"========== CLASS DISTRIBUTION ==========\")\n\ntotal = 0\n\nfor split in [\"train\", \"valid\", \"test\"]:\n    print(f\"\\n{split.upper()}\")\n\n    for class_name in classes:\n        folder = os.path.join(dataset_path, split, class_name)\n\n        count = len([\n            f for f in os.listdir(folder)\n            if f.lower().endswith((\".jpg\", \".jpeg\", \".png\", \".bmp\", \".webp\"))\n        ])\n\n        print(f\"{class_name}: {count}\")\n        total += count\n\nprint(\"\\nTotal Images:\", total)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:15:10.198946Z","iopub.execute_input":"2026-09-24T10:15:10.199891Z","iopub.status.idle":"2026-09-24T10:15:10.220781Z","shell.execute_reply.started":"2026-09-24T10:15:10.199853Z","shell.execute_reply":"2026-09-24T10:15:10.219647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nclasses = [\"autistic\", \"non_autistic\"]\n\nplt.figure(figsize=(10, 6))\n\nplot_index = 1\n\nfor class_name in classes:\n\n    folder = os.path.join(\n        dataset_path,\n        \"train\",\n        class_name\n    )\n\n    images = [\n        f for f in os.listdir(folder)\n        if f.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\", \".bmp\", \".webp\")\n        )\n    ]\n\n    selected_images = random.sample(\n        images,\n        min(4, len(images))\n    )\n\n    for image_name in selected_images:\n\n        image_path = os.path.join(\n            folder,\n            image_name\n        )\n\n        image = Image.open(image_path).convert(\"RGB\")\n\n        plt.subplot(2, 4, plot_index)\n        plt.imshow(image)\n        plt.title(class_name)\n        plt.axis(\"off\")\n\n        plot_index += 1\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:15:51.094299Z","iopub.execute_input":"2026-09-24T10:15:51.094697Z","iopub.status.idle":"2026-09-24T10:15:52.065918Z","shell.execute_reply.started":"2026-09-24T10:15:51.094668Z","shell.execute_reply":"2026-09-24T10:15:52.064944Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfrom PIL import Image\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nsplits = [\"train\", \"valid\", \"test\"]\nclasses = [\"autistic\", \"non_autistic\"]\n\ncorrupted_images = []\nvalid_images = 0\n\nfor split in splits:\n\n    for class_name in classes:\n\n        folder = os.path.join(\n            dataset_path,\n            split,\n            class_name\n        )\n\n        for image_name in os.listdir(folder):\n\n            if not image_name.lower().endswith(\n                (\".jpg\", \".jpeg\", \".png\", \".bmp\", \".webp\")\n            ):\n                continue\n\n            image_path = os.path.join(\n                folder,\n                image_name\n            )\n\n            try:\n                with Image.open(image_path) as img:\n                    img.verify()\n\n                valid_images += 1\n\n            except Exception:\n                corrupted_images.append(image_path)\n\nprint(\"Valid Images:\", valid_images)\nprint(\"Corrupted Images:\", len(corrupted_images))\n\nif corrupted_images:\n    print(\"\\nCorrupted Images:\")\n    for image in corrupted_images:\n        print(image)\nelse:\n    print(\"\\nNo corrupted images found.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:17:15.076595Z","iopub.execute_input":"2026-09-24T10:17:15.077571Z","iopub.status.idle":"2026-09-24T10:17:56.393089Z","shell.execute_reply.started":"2026-09-24T10:17:15.077538Z","shell.execute_reply":"2026-09-24T10:17:56.39202Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nclasses = [\"autistic\", \"non_autistic\"]\n\nface_cascade = cv2.CascadeClassifier(\n    cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\"\n)\n\nplt.figure(figsize=(12, 6))\nplot_index = 1\n\nfor class_name in classes:\n\n    folder = os.path.join(\n        dataset_path, \"train\", class_name\n    )\n\n    images = [\n        f for f in os.listdir(folder)\n        if f.lower().endswith((\".jpg\", \".jpeg\", \".png\"))\n    ]\n\n    for image_name in images[:3]:\n\n        image_path = os.path.join(folder, image_name)\n        image = cv2.imread(image_path)\n\n        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n        faces = face_cascade.detectMultiScale(\n            gray,\n            scaleFactor=1.1,\n            minNeighbors=5,\n            minSize=(30, 30)\n        )\n\n        if len(faces) > 0:\n\n            x, y, w, h = max(\n                faces,\n                key=lambda r: r[2] * r[3]\n            )\n\n            face = image[y:y+h, x:x+w]\n            face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n\n            plt.subplot(2, 3, plot_index)\n            plt.imshow(face)\n            plt.title(class_name)\n            plt.axis(\"off\")\n\n            plot_index += 1\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:20:54.534218Z","iopub.execute_input":"2026-09-24T10:20:54.534517Z","iopub.status.idle":"2026-09-24T10:20:54.999559Z","shell.execute_reply.started":"2026-09-24T10:20:54.534484Z","shell.execute_reply":"2026-09-24T10:20:54.99831Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nclasses = [\"autistic\", \"non_autistic\"]\n\nplt.figure(figsize=(12, 6))\nplot_index = 1\n\nfor class_name in classes:\n\n    folder = os.path.join(\n        dataset_path, \"train\", class_name\n    )\n\n    images = [\n        f for f in os.listdir(folder)\n        if f.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\")\n        )\n    ]\n\n    for image_name in images[:3]:\n\n        image_path = os.path.join(folder, image_name)\n\n        image = cv2.imread(image_path)\n\n        image = cv2.cvtColor(\n            image,\n            cv2.COLOR_BGR2RGB\n        )\n\n        resized = cv2.resize(\n            image,\n            (224, 224)\n        )\n\n        normalized = resized / 255.0\n\n        plt.subplot(2, 3, plot_index)\n        plt.imshow(normalized)\n        plt.title(class_name)\n        plt.axis(\"off\")\n\n        plot_index += 1\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:21:42.870542Z","iopub.execute_input":"2026-09-24T10:21:42.870882Z","iopub.status.idle":"2026-09-24T10:21:43.63888Z","shell.execute_reply.started":"2026-09-24T10:21:42.870855Z","shell.execute_reply":"2026-09-24T10:21:43.6377Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nclasses = [\"autistic\", \"non_autistic\"]\n\nplt.figure(figsize=(12, 6))\nplot_index = 1\n\nfor class_name in classes:\n\n    folder = os.path.join(\n        dataset_path, \"train\", class_name\n    )\n\n    images = [\n        f for f in os.listdir(folder)\n        if f.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\")\n        )\n    ]\n\n    image_path = os.path.join(folder, images[0])\n\n    image = cv2.imread(image_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = cv2.resize(image, (224, 224))\n\n    augmented = cv2.flip(image, 1)\n\n    plt.subplot(2, 3, plot_index)\n    plt.imshow(image)\n    plt.title(class_name + \" - Original\")\n    plt.axis(\"off\")\n    plot_index += 1\n\n    plt.subplot(2, 3, plot_index)\n    plt.imshow(augmented)\n    plt.title(class_name + \" - Augmented\")\n    plt.axis(\"off\")\n    plot_index += 1\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:23:07.909667Z","iopub.execute_input":"2026-09-24T10:23:07.910039Z","iopub.status.idle":"2026-09-24T10:23:08.367335Z","shell.execute_reply.started":"2026-09-24T10:23:07.910009Z","shell.execute_reply":"2026-09-24T10:23:08.36604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nsplits = [\"train\", \"valid\", \"test\"]\nclasses = [\"autistic\", \"non_autistic\"]\n\nprint(\"========== DATASET SPLIT VERIFICATION ==========\\n\")\n\nfor split in splits:\n\n    print(\"Split:\", split)\n\n    total = 0\n\n    for class_name in classes:\n\n        folder = os.path.join(\n            dataset_path,\n            split,\n            class_name\n        )\n\n        images = [\n            f for f in os.listdir(folder)\n            if f.lower().endswith(\n                (\".jpg\", \".jpeg\", \".png\", \".bmp\", \".webp\")\n            )\n        ]\n\n        print(class_name, \":\", len(images))\n\n        total += len(images)\n\n    print(\"Total:\", total)\n    print(\"-\" * 50)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:24:14.333541Z","iopub.execute_input":"2026-09-24T10:24:14.33389Z","iopub.status.idle":"2026-09-24T10:24:14.350469Z","shell.execute_reply.started":"2026-09-24T10:24:14.333863Z","shell.execute_reply":"2026-09-24T10:24:14.349664Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nfrom torchvision import models\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel = models.efficientnet_b0(\n    weights=models.EfficientNet_B0_Weights.DEFAULT\n)\n\nmodel.classifier[1] = nn.Linear(\n    model.classifier[1].in_features,\n    2\n)\n\nmodel = model.to(device)\n\nlayers = []\nparameters = []\n\nfor name, layer in model.named_children():\n    layers.append(name)\n    parameters.append(sum(p.numel() for p in layer.parameters()))\n\nplt.figure(figsize=(10, 5))\n\nplt.bar(layers, parameters)\n\nplt.title(\"EfficientNet-B0 Architecture\")\nplt.xlabel(\"Network Blocks\")\nplt.ylabel(\"Number of Parameters\")\n\nplt.xticks(rotation=45)\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:26:07.801349Z","iopub.execute_input":"2026-09-24T10:26:07.802358Z","iopub.status.idle":"2026-09-24T10:26:08.11676Z","shell.execute_reply.started":"2026-09-24T10:26:07.802309Z","shell.execute_reply":"2026-09-24T10:26:08.115914Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport torch\nimport matplotlib.pyplot as plt\nfrom torchvision import models\n\ndataset_path = \"/kaggle/input/datasets/prayashdas/autistic-children-facial-image-dataset\"\n\nclasses = [\"autistic\", \"non_autistic\"]\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel = models.efficientnet_b0(\n    weights=models.EfficientNet_B0_Weights.DEFAULT\n)\n\nfeature_extractor = model.features.to(device)\nfeature_extractor.eval()\n\nface_cascade = cv2.CascadeClassifier(\n    cv2.data.haarcascades +\n    \"haarcascade_frontalface_default.xml\"\n)\n\nplt.figure(figsize=(15, 8))\n\nplot_index = 1\n\nfor class_name in classes:\n\n    folder = os.path.join(\n        dataset_path,\n        \"train\",\n        class_name\n    )\n\n    images = [\n        f for f in os.listdir(folder)\n        if f.lower().endswith(\n            (\".jpg\", \".jpeg\", \".png\")\n        )\n    ]\n\n    for image_name in images[:3]:\n\n        image_path = os.path.join(folder, image_name)\n\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(\n            image,\n            cv2.COLOR_BGR2RGB\n        )\n\n        gray = cv2.cvtColor(\n            image,\n            cv2.COLOR_RGB2GRAY\n        )\n\n        faces = face_cascade.detectMultiScale(\n            gray,\n            1.1,\n            5\n        )\n\n        if len(faces) > 0:\n\n            x, y, w, h = max(\n                faces,\n                key=lambda r: r[2] * r[3]\n            )\n\n            face = image[y:y+h, x:x+w]\n\n        else:\n            face = image\n\n        face = cv2.resize(\n            face,\n            (224, 224)\n        )\n\n        tensor = torch.tensor(\n            face / 255.0,\n            dtype=torch.float32\n        ).permute(2, 0, 1).unsqueeze(0).to(device)\n\n        with torch.no_grad():\n            features = feature_extractor(tensor)\n\n        feature_map = features[0].mean(\n            dim=0\n        ).cpu().numpy()\n\n        # Original Image\n        plt.subplot(2, 9, plot_index)\n        plt.imshow(image)\n        plt.title(\"Original\")\n        plt.axis(\"off\")\n        plot_index += 1\n\n        # Face Cropped Image\n        plt.subplot(2, 9, plot_index)\n        plt.imshow(face)\n        plt.title(\"Face Crop\")\n        plt.axis(\"off\")\n        plot_index += 1\n\n        # Deep Feature Image\n        plt.subplot(2, 9, plot_index)\n        plt.imshow(feature_map, cmap=\"viridis\")\n        plt.title(\"Deep Feature\")\n        plt.axis(\"off\")\n        plot_index += 1\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:28:20.719886Z","iopub.execute_input":"2026-09-24T10:28:20.72057Z","iopub.status.idle":"2026-09-24T10:28:22.455862Z","shell.execute_reply.started":"2026-09-24T10:28:20.720529Z","shell.execute_reply":"2026-09-24T10:28:22.45475Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\n\niq_path = \"/kaggle/input/competitions/abide/comp_data/pheno_train.csv\"\n\ndf = pd.read_csv(iq_path)\n\n# Select child participants\ndf = df[df[\"AGE_AT_SCAN\"] <= 18].copy()\n\n# Select required multimodal IQ features\nfeatures = [\n    \"AGE_AT_SCAN\",\n    \"SEX\",\n    \"FIQ\",\n    \"VIQ\",\n    \"PIQ\"\n]\n\ndf_iq = df[features + [\"DX_GROUP\"]].copy()\n\n# Remove missing IQ values\ndf_iq = df_iq.dropna(\n    subset=[\"FIQ\", \"VIQ\", \"PIQ\"]\n)\n\n# Encode labels\ndf_iq[\"DX_GROUP\"] = df_iq[\"DX_GROUP\"].map({\n    1: 1,\n    2: 0\n})\n\nprint(\"IQ Dataset Shape:\", df_iq.shape)\nprint(\"\\nClass Distribution:\")\nprint(df_iq[\"DX_GROUP\"].value_counts())\n\n# Plot class distribution\nplt.figure(figsize=(6, 5))\n\ndf_iq[\"DX_GROUP\"].value_counts().sort_index().plot(\n    kind=\"bar\"\n)\n\nplt.title(\"IQ Dataset Class Distribution\")\nplt.xlabel(\"Class\")\nplt.ylabel(\"Number of Children\")\n\nplt.xticks(\n    [0, 1],\n    [\"Non-ASD\", \"ASD\"],\n    rotation=0\n)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:29:24.813336Z","iopub.execute_input":"2026-09-24T10:29:24.814275Z","iopub.status.idle":"2026-09-24T10:29:25.079699Z","shell.execute_reply.started":"2026-09-24T10:29:24.814238Z","shell.execute_reply":"2026-09-24T10:29:25.078988Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\n\niq_path = \"/kaggle/input/competitions/abide/comp_data/pheno_train.csv\"\n\ndf = pd.read_csv(iq_path)\n\ndf = df[df[\"AGE_AT_SCAN\"] <= 18].copy()\n\nfeatures = [\n    \"AGE_AT_SCAN\",\n    \"SEX\",\n    \"FIQ\",\n    \"VIQ\",\n    \"PIQ\"\n]\n\ndf_iq = df[features + [\"DX_GROUP\"]].copy()\n\ndf_iq = df_iq.dropna(\n    subset=[\"FIQ\", \"VIQ\", \"PIQ\"]\n)\n\ndf_iq[\"DX_GROUP\"] = df_iq[\"DX_GROUP\"].map({\n    1: 1,\n    2: 0\n})\n\nX = df_iq[features].copy()\ny = df_iq[\"DX_GROUP\"].values\n\n# Encode SEX\nX[\"SEX\"] = X[\"SEX\"].map({\n    \"M\": 1,\n    \"F\": 0\n})\n\nX[\"SEX\"] = X[\"SEX\"].fillna(\n    X[\"SEX\"].median()\n)\n\n# Normalize IQ features\nscaler = StandardScaler()\n\nX_scaled = scaler.fit_transform(X)\n\nX_scaled = pd.DataFrame(\n    X_scaled,\n    columns=features\n)\n\nprint(\"Normalized IQ Features:\")\nprint(X_scaled.head())\n\n# Plot feature distributions\nX_scaled.plot(\n    kind=\"box\",\n    figsize=(10, 5)\n)\n\nplt.title(\"Normalized IQ Feature Distribution\")\nplt.ylabel(\"Standardized Value\")\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:30:32.97258Z","iopub.execute_input":"2026-09-24T10:30:32.973371Z","iopub.status.idle":"2026-09-24T10:30:33.927378Z","shell.execute_reply.started":"2026-09-24T10:30:32.973338Z","shell.execute_reply":"2026-09-24T10:30:33.926474Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\n# Remove NaN and Inf values\nface_data = np.nan_to_num(\n    face_data,\n    nan=0.0,\n    posinf=0.0,\n    neginf=0.0\n)\n\niq_data = np.nan_to_num(\n    iq_data,\n    nan=0.0,\n    posinf=0.0,\n    neginf=0.0\n)\n\n# Match number of samples\nn = min(\n    len(face_data),\n    len(iq_data)\n)\n\nface_data = face_data[:n]\niq_data = iq_data[:n]\nlabels = np.asarray(y[:n])\n\n# Scale features\nface_scaled = StandardScaler().fit_transform(\n    face_data\n)\n\niq_scaled = StandardScaler().fit_transform(\n    iq_data\n)\n\n# Multimodal feature fusion\nfused_data = np.concatenate(\n    [face_scaled, iq_scaled],\n    axis=1\n)\n\n# Final NaN check\nfused_data = np.nan_to_num(\n    fused_data,\n    nan=0.0,\n    posinf=0.0,\n    neginf=0.0\n)\n\n# PCA\npca = PCA(n_components=2)\n\nfused_2d = pca.fit_transform(\n    fused_data\n)\n\n# Plot\nplt.figure(figsize=(10, 7))\n\nfor label, name in [\n    (0, \"Non-ASD\"),\n    (1, \"ASD\")\n]:\n\n    mask = labels == label\n\n    plt.scatter(\n        fused_2d[mask, 0],\n        fused_2d[mask, 1],\n        label=name,\n        alpha=0.7,\n        s=45\n    )\n\nplt.title(\n    \"Multimodal Feature Fusion using PCA\"\n)\n\nplt.xlabel(\n    \"Principal Component 1\"\n)\n\nplt.ylabel(\n    \"Principal Component 2\"\n)\n\nplt.legend()\nplt.grid(alpha=0.3)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:53:46.928942Z","iopub.execute_input":"2026-09-24T10:53:46.929672Z","iopub.status.idle":"2026-09-24T10:53:47.415561Z","shell.execute_reply.started":"2026-09-24T10:53:46.929617Z","shell.execute_reply":"2026-09-24T10:53:47.414435Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# Average attention weights\nattn = attention_weights.detach().cpu().numpy()\n\nif attn.ndim == 4:\n    attn = attn.mean(axis=1)\n\nif attn.ndim == 3:\n    attn = attn.mean(axis=0)\n\n# Create 2 × 2 modality attention matrix\nattention_matrix = np.array([\n    [attn[0, 0], attn[0, 1]],\n    [attn[1, 0], attn[1, 1]]\n])\n\nplt.figure(figsize=(7, 6))\n\nplt.imshow(\n    attention_matrix,\n    cmap=\"hot\",\n    interpolation=\"nearest\"\n)\n\nplt.xticks(\n    [0, 1],\n    [\"Face\", \"IQ\"],\n    fontsize=12\n)\n\nplt.yticks(\n    [0, 1],\n    [\"Face\", \"IQ\"],\n    fontsize=12\n)\n\nplt.xlabel(\"Attended Modality\")\nplt.ylabel(\"Input Modality\")\n\nplt.title(\n    \"Attention-Based Multimodal Interaction\"\n)\n\nfor i in range(2):\n    for j in range(2):\n        plt.text(\n            j,\n            i,\n            f\"{attention_matrix[i, j]:.3f}\",\n            ha=\"center\",\n            va=\"center\",\n            fontsize=14\n        )\n\nplt.colorbar(\n    label=\"Attention Weight\"\n)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:55:26.579919Z","iopub.execute_input":"2026-09-24T10:55:26.580754Z","iopub.status.idle":"2026-09-24T10:55:26.767707Z","shell.execute_reply.started":"2026-09-24T10:55:26.580701Z","shell.execute_reply":"2026-09-24T10:55:26.766933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nX = attention_features.detach()\nY = torch.tensor(\n    labels,\n    dtype=torch.long\n)\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X,\n    Y,\n    test_size=0.2,\n    random_state=42,\n    stratify=Y\n)\n\nclass FusionClassifier(nn.Module):\n\n    def __init__(self):\n        super().__init__()\n\n        self.classifier = nn.Sequential(\n            nn.Linear(128, 64),\n            nn.ReLU(),\n            nn.Dropout(0.3),\n\n            nn.Linear(64, 32),\n            nn.ReLU(),\n\n            nn.Linear(32, 2)\n        )\n\n    def forward(self, x):\n        return self.classifier(x)\n\n\nclassifier = FusionClassifier()\n\ncriterion = nn.CrossEntropyLoss()\n\noptimizer = optim.Adam(\n    classifier.parameters(),\n    lr=0.001\n)\n\nepochs = 30\n\ntrain_loss = []\ntrain_accuracy = []\n\nfor epoch in range(epochs):\n\n    classifier.train()\n\n    optimizer.zero_grad()\n\n    output = classifier(X_train)\n\n    loss = criterion(\n        output,\n        y_train\n    )\n\n    loss.backward()\n\n    optimizer.step()\n\n    predictions = torch.argmax(\n        output,\n        dim=1\n    )\n\n    accuracy = (\n        predictions == y_train\n    ).float().mean().item()\n\n    train_loss.append(\n        loss.item()\n    )\n\n    train_accuracy.append(\n        accuracy\n    )\n\n    print(\n        f\"Epoch [{epoch+1}/{epochs}] \"\n        f\"Loss: {loss.item():.4f} \"\n        f\"Accuracy: {accuracy:.4f}\"\n    )\n\n# Training Loss Plot\nplt.figure(figsize=(10, 5))\n\nplt.plot(\n    range(1, epochs + 1),\n    train_loss,\n    marker=\"o\"\n)\n\nplt.title(\n    \"Multimodal Fusion Classifier Training Loss\"\n)\n\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\n\nplt.grid(True)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:56:21.858986Z","iopub.execute_input":"2026-09-24T10:56:21.859325Z","iopub.status.idle":"2026-09-24T10:56:22.178435Z","shell.execute_reply.started":"2026-09-24T10:56:21.859296Z","shell.execute_reply":"2026-09-24T10:56:22.177148Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\n\n# Improved classifier\nclassifier = nn.Sequential(\n    nn.Linear(128, 256),\n    nn.ReLU(),\n    nn.Dropout(0.1),\n\n    nn.Linear(256, 128),\n    nn.ReLU(),\n    nn.Dropout(0.1),\n\n    nn.Linear(128, 64),\n    nn.ReLU(),\n\n    nn.Linear(64, 2)\n)\n\ncriterion = nn.CrossEntropyLoss()\n\noptimizer = optim.AdamW(\n    classifier.parameters(),\n    lr=0.0003,\n    weight_decay=1e-5\n)\n\nepochs = 150\n\naccuracy_history = []\n\nfor epoch in range(epochs):\n\n    classifier.train()\n\n    optimizer.zero_grad()\n\n    output = classifier(X_train)\n\n    loss = criterion(\n        output,\n        y_train\n    )\n\n    loss.backward()\n    optimizer.step()\n\n    pred = torch.argmax(\n        output,\n        dim=1\n    )\n\n    accuracy = (\n        pred == y_train\n    ).float().mean().item()\n\n    accuracy_history.append(\n        accuracy * 100\n    )\n\n    if (epoch + 1) % 10 == 0:\n        print(\n            f\"Epoch {epoch+1:03d} | \"\n            f\"Accuracy: {accuracy*100:.2f}%\"\n        )\n\n# Accuracy Plot\nplt.figure(figsize=(10, 5))\n\nplt.plot(\n    accuracy_history,\n    linewidth=2\n)\n\nplt.title(\n    \"Multimodal Model Accuracy\"\n)\n\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy (%)\")\n\nplt.ylim(\n    max(0, min(accuracy_history) - 5),\n    100\n)\n\nplt.grid(True)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:59:29.41417Z","iopub.execute_input":"2026-09-24T10:59:29.414568Z","iopub.status.idle":"2026-09-24T10:59:30.666019Z","shell.execute_reply.started":"2026-09-24T10:59:29.414536Z","shell.execute_reply":"2026-09-24T10:59:30.664953Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import (\n    accuracy_score,\n    precision_score,\n    recall_score,\n    f1_score,\n    roc_auc_score\n)\n\nclassifier.eval()\n\nwith torch.no_grad():\n\n    output = classifier(X_test)\n\n    probabilities = torch.softmax(\n        output,\n        dim=1\n    )[:, 1]\n\n    predictions = torch.argmax(\n        output,\n        dim=1\n    )\n\ny_true = y_test.cpu().numpy()\ny_pred = predictions.cpu().numpy()\ny_prob = probabilities.cpu().numpy()\n\naccuracy = accuracy_score(\n    y_true,\n    y_pred\n) * 100\n\nprecision = precision_score(\n    y_true,\n    y_pred,\n    zero_division=0\n) * 100\n\nrecall = recall_score(\n    y_true,\n    y_pred,\n    zero_division=0\n) * 100\n\nf1 = f1_score(\n    y_true,\n    y_pred,\n    zero_division=0\n) * 100\n\nroc_auc = roc_auc_score(\n    y_true,\n    y_prob\n) * 100\n\nmetrics = [\n    accuracy,\n    precision,\n    recall,\n    f1,\n    roc_auc\n]\n\nnames = [\n    \"Accuracy\",\n    \"Precision\",\n    \"Recall\",\n    \"F1-Score\",\n    \"ROC-AUC\"\n]\n\nplt.figure(figsize=(10, 6))\n\nbars = plt.bar(\n    names,\n    metrics\n)\n\nplt.ylim(0, 100)\n\nplt.ylabel(\"Percentage (%)\")\nplt.title(\"Multimodal ASD Detection Performance\")\n\nfor bar, value in zip(bars, metrics):\n\n    plt.text(\n        bar.get_x() + bar.get_width() / 2,\n        value + 1,\n        f\"{value:.2f}%\",\n        ha=\"center\",\n        fontweight=\"bold\"\n    )\n\nplt.grid(\n    axis=\"y\",\n    alpha=0.3\n)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T11:00:27.765076Z","iopub.execute_input":"2026-09-24T11:00:27.765394Z","iopub.status.idle":"2026-09-24T11:00:27.971134Z","shell.execute_reply.started":"2026-09-24T11:00:27.765369Z","shell.execute_reply":"2026-09-24T11:00:27.969947Z"}},"outputs":[],"execution_count":null}]}