mobadara commited on
Commit
b7cdfc0
·
1 Parent(s): e446f59

Created using Colab

Browse files
notebooks/01_model_training_and_fine_tuning.ipynb CHANGED
@@ -5,7 +5,7 @@
5
  "colab": {
6
  "provenance": [],
7
  "gpuType": "T4",
8
- "authorship_tag": "ABX9TyPSiHqZC3XJwRUnsyWT6QPo",
9
  "include_colab_link": true
10
  },
11
  "kernelspec": {
@@ -51,12 +51,12 @@
51
  "metadata": {
52
  "id": "OwBert5NpQwF"
53
  },
54
- "execution_count": 5,
55
  "outputs": []
56
  },
57
  {
58
  "cell_type": "code",
59
- "execution_count": 9,
60
  "metadata": {
61
  "colab": {
62
  "base_uri": "https://localhost:8080/"
@@ -143,7 +143,7 @@
143
  "id": "ikceEotXOU_1",
144
  "outputId": "077395cc-6cf0-42f5-e0b3-65a1e322b5a8"
145
  },
146
- "execution_count": 2,
147
  "outputs": [
148
  {
149
  "output_type": "stream",
@@ -199,7 +199,7 @@
199
  },
200
  "outputId": "3a3b35dc-01e5-4980-bdfc-0958467a5f24"
201
  },
202
- "execution_count": 3,
203
  "outputs": [
204
  {
205
  "output_type": "stream",
@@ -274,7 +274,7 @@
274
  "id": "3cTqFqcvnVG2",
275
  "outputId": "19533754-f990-4485-b848-d9c2be3f782b"
276
  },
277
- "execution_count": 7,
278
  "outputs": [
279
  {
280
  "output_type": "stream",
@@ -405,7 +405,7 @@
405
  "id": "HrV6nUsjodCM",
406
  "outputId": "ff77d837-8183-4f16-ea06-4979fd6e540a"
407
  },
408
- "execution_count": 8,
409
  "outputs": [
410
  {
411
  "output_type": "stream",
@@ -523,7 +523,7 @@
523
  "height": 773
524
  }
525
  },
526
- "execution_count": 10,
527
  "outputs": [
528
  {
529
  "output_type": "stream",
@@ -591,6 +591,163 @@
591
  "id": "DWEkHU0AzaZJ"
592
  }
593
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  {
595
  "cell_type": "markdown",
596
  "source": [
 
5
  "colab": {
6
  "provenance": [],
7
  "gpuType": "T4",
8
+ "authorship_tag": "ABX9TyM7c25lrmEww8m7ZUcLm9mv",
9
  "include_colab_link": true
10
  },
11
  "kernelspec": {
 
51
  "metadata": {
52
  "id": "OwBert5NpQwF"
53
  },
54
+ "execution_count": null,
55
  "outputs": []
56
  },
57
  {
58
  "cell_type": "code",
59
+ "execution_count": null,
60
  "metadata": {
61
  "colab": {
62
  "base_uri": "https://localhost:8080/"
 
143
  "id": "ikceEotXOU_1",
144
  "outputId": "077395cc-6cf0-42f5-e0b3-65a1e322b5a8"
145
  },
146
+ "execution_count": null,
147
  "outputs": [
148
  {
149
  "output_type": "stream",
 
199
  },
200
  "outputId": "3a3b35dc-01e5-4980-bdfc-0958467a5f24"
201
  },
202
+ "execution_count": null,
203
  "outputs": [
204
  {
205
  "output_type": "stream",
 
274
  "id": "3cTqFqcvnVG2",
275
  "outputId": "19533754-f990-4485-b848-d9c2be3f782b"
276
  },
277
+ "execution_count": null,
278
  "outputs": [
279
  {
280
  "output_type": "stream",
 
405
  "id": "HrV6nUsjodCM",
406
  "outputId": "ff77d837-8183-4f16-ea06-4979fd6e540a"
407
  },
408
+ "execution_count": null,
409
  "outputs": [
410
  {
411
  "output_type": "stream",
 
523
  "height": 773
524
  }
525
  },
526
+ "execution_count": null,
527
  "outputs": [
528
  {
529
  "output_type": "stream",
 
591
  "id": "DWEkHU0AzaZJ"
592
  }
593
  },
594
+ {
595
+ "cell_type": "markdown",
596
+ "source": [
597
+ "## **Hugging Face**"
598
+ ],
599
+ "metadata": {
600
+ "id": "fjado_xqZDQJ"
601
+ }
602
+ },
603
+ {
604
+ "cell_type": "code",
605
+ "source": [
606
+ "# 1. Retrieve the token (Checks Colab Secrets first, then Environment variables)\n",
607
+ "try:\n",
608
+ " hf_token = userdata.get('HF_TOKEN')\n",
609
+ "except userdata.SecretNotFoundError:\n",
610
+ " hf_token = os.environ.get(\"HF_TOKEN\")\n",
611
+ "\n",
612
+ "if not hf_token:\n",
613
+ " raise ValueError(\"HF_TOKEN not found! Please set it in Colab Secrets or export it.\")\n",
614
+ "\n",
615
+ "# 2. Define your repository setup\n",
616
+ "hf_username = \"<YOUR_HF_USERNAME>\" # e.g., mobadara\n",
617
+ "repo_name = \"pneumonia-densenet121\"\n",
618
+ "repo_id = f\"{hf_username}/{repo_name}\"\n",
619
+ "model_path = \"densenet_pneumonia_finetuned.pth\"\n",
620
+ "\n",
621
+ "# 3. Create the repository\n",
622
+ "api = HfApi(token=hf_token)\n",
623
+ "print(f\"Creating/Checking repository: {repo_id}...\")\n",
624
+ "create_repo(repo_id=repo_id, token=hf_token, exist_ok=True)\n",
625
+ "\n",
626
+ "# 4. Generate the Model Card with YAML Metadata\n",
627
+ "model_card_content = \"\"\"---\n",
628
+ "language: en\n",
629
+ "license: mit\n",
630
+ "tags:\n",
631
+ "- image-classification\n",
632
+ "- vision\n",
633
+ "- pytorch\n",
634
+ "- densenet\n",
635
+ "- medical\n",
636
+ "- healthcare\n",
637
+ "datasets:\n",
638
+ "- paultimothymooney/chest-xray-pneumonia\n",
639
+ "metrics:\n",
640
+ "- accuracy\n",
641
+ "- recall\n",
642
+ "---\n",
643
+ "# DenseNet121 - Pediatric Pneumonia Detection\n",
644
+ "\n",
645
+ "## Model Description\n",
646
+ "This is a fine-tuned DenseNet121 model trained to classify chest X-rays into two categories: **NORMAL** and **PNEUMONIA**. It was developed as part of a precision diagnostics AI pipeline to assist clinical workflows.\n",
647
+ "\n",
648
+ "To handle the severe class imbalance inherent in the dataset, dynamic class weights were applied to the PyTorch `CrossEntropyLoss` function, heavily penalizing false negatives to prioritize patient safety.\n",
649
+ "\n",
650
+ "## Intended Uses & Limitations\n",
651
+ "* **Intended Use:** As an auxiliary tool for clinical triage and radiologist workflow acceleration. It is designed to be paired with explainability tools (like Grad-CAM) to provide visual context.\n",
652
+ "* **Limitations:** This model is a research prototype and is not FDA-approved. It should not be used as a standalone diagnostic tool.\n",
653
+ "\n",
654
+ "## Training Data\n",
655
+ "Trained on the Kaggle Chest X-Ray Images (Pneumonia) dataset. All images were normalized and resized to 224x224. Light data augmentation (rotation and color jittering) was applied to the training set to prevent overfitting.\n",
656
+ "\n",
657
+ "## Evaluation Results\n",
658
+ "The model was evaluated on a completely unseen test dataset consisting of 624 images.\n",
659
+ "* **Overall Accuracy:** 86.4%\n",
660
+ "* **Pneumonia Recall (Sensitivity):** 94.6% (Successfully identified 369 out of 390 sick patients)\n",
661
+ "\n",
662
+ "The high recall indicates the model heavily prioritizes catching pathology, treating false positives as an acceptable clinical trade-off requiring secondary physician review.\n",
663
+ "\"\"\"\n",
664
+ "\n",
665
+ "# Save the card locally\n",
666
+ "with open(\"README.md\", \"w\") as f:\n",
667
+ " f.write(model_card_content)\n",
668
+ "\n",
669
+ "# 5. Upload the files\n",
670
+ "print(\"Uploading Model Weights...\")\n",
671
+ "api.upload_file(\n",
672
+ " path_or_fileobj=model_path,\n",
673
+ " path_in_repo=model_path,\n",
674
+ " repo_id=repo_id,\n",
675
+ " commit_message=\"Initial push: Fine-tuned DenseNet weights\"\n",
676
+ ")\n",
677
+ "\n",
678
+ "print(\"Uploading Model Card...\")\n",
679
+ "api.upload_file(\n",
680
+ " path_or_fileobj=\"README.md\",\n",
681
+ " path_in_repo=\"README.md\",\n",
682
+ " repo_id=repo_id,\n",
683
+ " commit_message=\"Add professional model card with YAML metadata\"\n",
684
+ ")\n",
685
+ "\n",
686
+ "print(f\"✅ Successfully deployed to Hugging Face! View it here: https://huggingface.co/{repo_id}\")"
687
+ ],
688
+ "metadata": {
689
+ "id": "Dwm-2sodZCUk"
690
+ },
691
+ "execution_count": null,
692
+ "outputs": []
693
+ },
694
+ {
695
+ "cell_type": "markdown",
696
+ "source": [
697
+ "## **GitHub Release**"
698
+ ],
699
+ "metadata": {
700
+ "id": "Javrpd_gZZiK"
701
+ }
702
+ },
703
+ {
704
+ "cell_type": "code",
705
+ "source": [
706
+ "# Safely extract the token and assign it to an environment variable\n",
707
+ "os.environ[\"GITHUB_TOKEN\"] = userdata.get(\"GITHUB_TOKEN\")\n",
708
+ "print(\"✅ Token securely loaded into environment!\")"
709
+ ],
710
+ "metadata": {
711
+ "id": "Uq2QnjXJZr_g"
712
+ },
713
+ "execution_count": null,
714
+ "outputs": []
715
+ },
716
+ {
717
+ "cell_type": "code",
718
+ "source": [
719
+ "%%bash\n",
720
+ "%%bash\n",
721
+ "# 1. Variables (Notice GITHUB_TOKEN is missing here, we read it directly from the environment!)\n",
722
+ "REPO_OWNER=\"mobadara\"\n",
723
+ "REPO_NAME=\"precision-diagnostics-xai\"\n",
724
+ "MODEL_FILE=\"densenet_pneumonia_finetuned.pth\"\n",
725
+ "TAG=\"v1.0.0\"\n",
726
+ "\n",
727
+ "# 2. Install the GitHub CLI into Colab\n",
728
+ "curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \\\n",
729
+ "&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \\\n",
730
+ "&& echo \"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main\" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \\\n",
731
+ "&& sudo apt update -q && sudo apt install gh -y -q\n",
732
+ "\n",
733
+ "# 3. Authenticate GitHub CLI securely using the environment variable\n",
734
+ "echo \"$GITHUB_TOKEN\" | gh auth login --with-token\n",
735
+ "\n",
736
+ "# 4. Create the Release and upload the file simultaneously\n",
737
+ "echo \"Creating GitHub Release $TAG...\"\n",
738
+ "gh release create $TAG $MODEL_FILE \\\n",
739
+ " --repo \"$REPO_OWNER/$REPO_NAME\" \\\n",
740
+ " --title \"v1.0.0 - Baseline DenseNet121 Model\" \\\n",
741
+ " --notes \"Initial release of the fine-tuned DenseNet121 weights for Pneumonia detection. Achieved 94.6% recall on the test set. File attached for backend deployment.\"\n",
742
+ "\n",
743
+ "echo \"✅ Successfully created GitHub Release and uploaded weights!\""
744
+ ],
745
+ "metadata": {
746
+ "id": "o4_40DdsZhIb"
747
+ },
748
+ "execution_count": null,
749
+ "outputs": []
750
+ },
751
  {
752
  "cell_type": "markdown",
753
  "source": [