File size: 35,426 Bytes
692e598 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Install"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Requirement already satisfied: uv in /Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages (0.1.42)\n",
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install uv"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[2mAudited \u001b[1m12 packages\u001b[0m in 8ms\u001b[0m\n"
]
}
],
"source": [
"!uv pip install dagshub setuptools accelerate toml torch torchvision transformers mlflow datasets ipywidgets python-dotenv evaluate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Setup"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Initialized MLflow to track repo <span style=\"color: #008000; text-decoration-color: #008000\">\"amaye15/CanineNet\"</span>\n",
"</pre>\n"
],
"text/plain": [
"Initialized MLflow to track repo \u001b[32m\"amaye15/CanineNet\"\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Repository amaye15/CanineNet initialized!\n",
"</pre>\n"
],
"text/plain": [
"Repository amaye15/CanineNet initialized!\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import os\n",
"import toml\n",
"import torch\n",
"import mlflow\n",
"import dagshub\n",
"import datasets\n",
"import evaluate\n",
"from dotenv import load_dotenv\n",
"from torchvision.transforms import v2\n",
"from transformers import AutoImageProcessor, AutoModelForImageClassification, TrainingArguments, Trainer\n",
"\n",
"ENV_PATH = \"/Users/andrewmayes/Openclassroom/CanineNet/.env\"\n",
"CONFIG_PATH = \"/Users/andrewmayes/Openclassroom/CanineNet/code/config.toml\"\n",
"CONFIG = toml.load(CONFIG_PATH)\n",
"\n",
"load_dotenv(ENV_PATH)\n",
"\n",
"dagshub.init(repo_name=os.environ['MLFLOW_TRACKING_PROJECTNAME'], repo_owner=os.environ['MLFLOW_TRACKING_USERNAME'], mlflow=True, dvc=True)\n",
"\n",
"os.environ['MLFLOW_TRACKING_USERNAME'] = \"amaye15\"\n",
"\n",
"mlflow.set_tracking_uri(f'https://dagshub.com/' + os.environ['MLFLOW_TRACKING_USERNAME']\n",
" + '/' + os.environ['MLFLOW_TRACKING_PROJECTNAME'] + '.mlflow')\n",
"\n",
"CREATE_DATASET = True\n",
"ORIGINAL_DATASET = \"Alanox/stanford-dogs\"\n",
"MODIFIED_DATASET = \"amaye15/stanford-dogs\"\n",
"REMOVE_COLUMNS = [\"name\", \"annotations\"]\n",
"RENAME_COLUMNS = {\"image\":\"pixel_values\", \"target\":\"label\"}\n",
"SPLIT = 0.2\n",
"\n",
"METRICS = [\"accuracy\", \"f1\", \"precision\", \"recall\"]\n",
"# MODELS = 'google/vit-base-patch16-224'\n",
"# MODELS = \"google/siglip-base-patch16-224\"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Dataset"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Affenpinscher: 0\n",
"Afghan Hound: 1\n",
"African Hunting Dog: 2\n",
"Airedale: 3\n",
"American Staffordshire Terrier: 4\n",
"Appenzeller: 5\n",
"Australian Terrier: 6\n",
"Basenji: 7\n",
"Basset: 8\n",
"Beagle: 9\n",
"Bedlington Terrier: 10\n",
"Bernese Mountain Dog: 11\n",
"Black And Tan Coonhound: 12\n",
"Blenheim Spaniel: 13\n",
"Bloodhound: 14\n",
"Bluetick: 15\n",
"Border Collie: 16\n",
"Border Terrier: 17\n",
"Borzoi: 18\n",
"Boston Bull: 19\n",
"Bouvier Des Flandres: 20\n",
"Boxer: 21\n",
"Brabancon Griffon: 22\n",
"Briard: 23\n",
"Brittany Spaniel: 24\n",
"Bull Mastiff: 25\n",
"Cairn: 26\n",
"Cardigan: 27\n",
"Chesapeake Bay Retriever: 28\n",
"Chihuahua: 29\n",
"Chow: 30\n",
"Clumber: 31\n",
"Cocker Spaniel: 32\n",
"Collie: 33\n",
"Curly Coated Retriever: 34\n",
"Dandie Dinmont: 35\n",
"Dhole: 36\n",
"Dingo: 37\n",
"Doberman: 38\n",
"English Foxhound: 39\n",
"English Setter: 40\n",
"English Springer: 41\n",
"Entlebucher: 42\n",
"Eskimo Dog: 43\n",
"Flat Coated Retriever: 44\n",
"French Bulldog: 45\n",
"German Shepherd: 46\n",
"German Short Haired Pointer: 47\n",
"Giant Schnauzer: 48\n",
"Golden Retriever: 49\n",
"Gordon Setter: 50\n",
"Great Dane: 51\n",
"Great Pyrenees: 52\n",
"Greater Swiss Mountain Dog: 53\n",
"Groenendael: 54\n",
"Ibizan Hound: 55\n",
"Irish Setter: 56\n",
"Irish Terrier: 57\n",
"Irish Water Spaniel: 58\n",
"Irish Wolfhound: 59\n",
"Italian Greyhound: 60\n",
"Japanese Spaniel: 61\n",
"Keeshond: 62\n",
"Kelpie: 63\n",
"Kerry Blue Terrier: 64\n",
"Komondor: 65\n",
"Kuvasz: 66\n",
"Labrador Retriever: 67\n",
"Lakeland Terrier: 68\n",
"Leonberg: 69\n",
"Lhasa: 70\n",
"Malamute: 71\n",
"Malinois: 72\n",
"Maltese Dog: 73\n",
"Mexican Hairless: 74\n",
"Miniature Pinscher: 75\n",
"Miniature Poodle: 76\n",
"Miniature Schnauzer: 77\n",
"Newfoundland: 78\n",
"Norfolk Terrier: 79\n",
"Norwegian Elkhound: 80\n",
"Norwich Terrier: 81\n",
"Old English Sheepdog: 82\n",
"Otterhound: 83\n",
"Papillon: 84\n",
"Pekinese: 85\n",
"Pembroke: 86\n",
"Pomeranian: 87\n",
"Pug: 88\n",
"Redbone: 89\n",
"Rhodesian Ridgeback: 90\n",
"Rottweiler: 91\n",
"Saint Bernard: 92\n",
"Saluki: 93\n",
"Samoyed: 94\n",
"Schipperke: 95\n",
"Scotch Terrier: 96\n",
"Scottish Deerhound: 97\n",
"Sealyham Terrier: 98\n",
"Shetland Sheepdog: 99\n",
"Shih Tzu: 100\n",
"Siberian Husky: 101\n",
"Silky Terrier: 102\n",
"Soft Coated Wheaten Terrier: 103\n",
"Staffordshire Bullterrier: 104\n",
"Standard Poodle: 105\n",
"Standard Schnauzer: 106\n",
"Sussex Spaniel: 107\n",
"Tibetan Mastiff: 108\n",
"Tibetan Terrier: 109\n",
"Toy Poodle: 110\n",
"Toy Terrier: 111\n",
"Vizsla: 112\n",
"Walker Hound: 113\n",
"Weimaraner: 114\n",
"Welsh Springer Spaniel: 115\n",
"West Highland White Terrier: 116\n",
"Whippet: 117\n",
"Wire Haired Fox Terrier: 118\n",
"Yorkshire Terrier: 119\n"
]
}
],
"source": [
"if CREATE_DATASET:\n",
" ds = datasets.load_dataset(ORIGINAL_DATASET, token=os.getenv(\"HF_TOKEN\"), split=\"full\", trust_remote_code=True)\n",
" ds = ds.remove_columns(REMOVE_COLUMNS).rename_columns(RENAME_COLUMNS)\n",
"\n",
" labels = ds.select_columns(\"label\").to_pandas().sort_values(\"label\").get(\"label\").unique().tolist()\n",
" numbers = range(len(labels))\n",
" label2int = dict(zip(labels, numbers))\n",
" int2label = dict(zip(numbers, labels))\n",
"\n",
" for key, val in label2int.items():\n",
" print(f\"{key}: {val}\")\n",
"\n",
" ds = ds.class_encode_column(\"label\")\n",
" ds = ds.align_labels_with_mapping(label2int, \"label\")\n",
"\n",
" ds = ds.train_test_split(test_size=SPLIT, stratify_by_column = \"label\")\n",
" #ds.push_to_hub(MODIFIED_DATASET, token=os.getenv(\"HF_TOKEN\"))\n",
"\n",
" CONFIG[\"label2int\"] = str(label2int)\n",
" CONFIG[\"int2label\"] = str(int2label)\n",
"\n",
" # with open(\"output.toml\", \"w\") as toml_file:\n",
" # toml.dump(toml.dumps(CONFIG), toml_file)\n",
"\n",
" #ds = datasets.load_dataset(MODIFIED_DATASET, token=os.getenv(\"HF_TOKEN\"), trust_remote_code=True, streaming=True)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-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",
"Could not find image processor class in the image processor config or the model config. Loading based on pattern matching with the model's feature extractor configuration. Please open a PR/issue to update `preprocessor_config.json` to use `image_processor_type` instead of `feature_extractor_type`. This warning will be removed in v4.40.\n",
"Some weights of ResNetForImageClassification were not initialized from the model checkpoint at microsoft/resnet-50 and are newly initialized because the shapes did not match:\n",
"- classifier.1.bias: found shape torch.Size([1000]) in the checkpoint and torch.Size([120]) in the model instantiated\n",
"- classifier.1.weight: found shape torch.Size([1000, 2048]) in the checkpoint and torch.Size([120, 2048]) in the model instantiated\n",
"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
"max_steps is given, it will override any value given in num_train_epochs\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "037a86c2839440679fcff5595079beac",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/1000 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'loss': 4.7829, 'grad_norm': 0.6043907999992371, 'learning_rate': 4.9500000000000004e-05, 'epoch': 0.08}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b1f85d03fadd4763a741fec5e5285d2a",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.77471923828125, 'eval_accuracy': 0.2118561710398445, 'eval_f1': 0.187375517726323, 'eval_precision': 0.3919036860239945, 'eval_recall': 0.19824327355121704, 'eval_runtime': 33.4309, 'eval_samples_per_second': 123.12, 'eval_steps_per_second': 3.859, 'epoch': 0.08}\n",
"{'loss': 4.7714, 'grad_norm': 0.6754865050315857, 'learning_rate': 4.9e-05, 'epoch': 0.16}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "268749f0d84a4fde98822b2ce1eead4f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.757228851318359, 'eval_accuracy': 0.20383867832847424, 'eval_f1': 0.18416981866925827, 'eval_precision': 0.42618136770448983, 'eval_recall': 0.18363998800713158, 'eval_runtime': 30.7622, 'eval_samples_per_second': 133.801, 'eval_steps_per_second': 4.193, 'epoch': 0.16}\n",
"{'loss': 4.7606, 'grad_norm': 0.6417286992073059, 'learning_rate': 4.85e-05, 'epoch': 0.23}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "907e888ac52d4fe18fb87cc1cfe2b22f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.736657619476318, 'eval_accuracy': 0.358600583090379, 'eval_f1': 0.3433113409864575, 'eval_precision': 0.6517178219942168, 'eval_recall': 0.3306848427836897, 'eval_runtime': 29.5337, 'eval_samples_per_second': 139.366, 'eval_steps_per_second': 4.368, 'epoch': 0.23}\n",
"{'loss': 4.747, 'grad_norm': 0.6243997812271118, 'learning_rate': 4.8e-05, 'epoch': 0.31}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "a2c7266f55814c86badb55ec9f3c12cc",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.714941501617432, 'eval_accuracy': 0.4302721088435374, 'eval_f1': 0.42721541071711805, 'eval_precision': 0.773414620851018, 'eval_recall': 0.40385862239180403, 'eval_runtime': 31.0076, 'eval_samples_per_second': 132.742, 'eval_steps_per_second': 4.16, 'epoch': 0.31}\n",
"{'loss': 4.7253, 'grad_norm': 0.6433669328689575, 'learning_rate': 4.75e-05, 'epoch': 0.39}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8a6ab27c180d4d68925da71fb6d734d8",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.684640884399414, 'eval_accuracy': 0.4361030126336249, 'eval_f1': 0.4677602303574034, 'eval_precision': 0.7906333558807621, 'eval_recall': 0.4160270614713831, 'eval_runtime': 31.2777, 'eval_samples_per_second': 131.595, 'eval_steps_per_second': 4.124, 'epoch': 0.39}\n",
"{'loss': 4.7069, 'grad_norm': 0.7207397818565369, 'learning_rate': 4.7e-05, 'epoch': 0.47}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ff7ef69b883549f988fda71b35cb9ef1",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.653403282165527, 'eval_accuracy': 0.533041788143829, 'eval_f1': 0.5396864056951644, 'eval_precision': 0.804847761263092, 'eval_recall': 0.5092981237432466, 'eval_runtime': 28.6761, 'eval_samples_per_second': 143.534, 'eval_steps_per_second': 4.499, 'epoch': 0.47}\n",
"{'loss': 4.6857, 'grad_norm': 0.7303667068481445, 'learning_rate': 4.6500000000000005e-05, 'epoch': 0.54}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c293ebbb0aec4666b6ad0d17517e2a29",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.617745399475098, 'eval_accuracy': 0.5500485908649174, 'eval_f1': 0.5511369002526866, 'eval_precision': 0.7998093864476505, 'eval_recall': 0.5263615811202424, 'eval_runtime': 28.5304, 'eval_samples_per_second': 144.267, 'eval_steps_per_second': 4.521, 'epoch': 0.54}\n",
"{'loss': 4.6569, 'grad_norm': 0.744701623916626, 'learning_rate': 4.600000000000001e-05, 'epoch': 0.62}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "53ce3795c47f4dd18f0f926d1532fb9a",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.576382160186768, 'eval_accuracy': 0.5738581146744413, 'eval_f1': 0.5800354551041117, 'eval_precision': 0.8207891649420048, 'eval_recall': 0.5516830965289926, 'eval_runtime': 28.9367, 'eval_samples_per_second': 142.241, 'eval_steps_per_second': 4.458, 'epoch': 0.62}\n",
"{'loss': 4.6293, 'grad_norm': 0.8225492238998413, 'learning_rate': 4.55e-05, 'epoch': 0.7}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "388b626051df4cde8bfacb4f10f53706",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.535852432250977, 'eval_accuracy': 0.6141885325558795, 'eval_f1': 0.6148517759248673, 'eval_precision': 0.807489842077252, 'eval_recall': 0.5926437581767611, 'eval_runtime': 29.8128, 'eval_samples_per_second': 138.062, 'eval_steps_per_second': 4.327, 'epoch': 0.7}\n",
"{'loss': 4.5953, 'grad_norm': 0.835442066192627, 'learning_rate': 4.5e-05, 'epoch': 0.78}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "0969f9351eae4472814238ff34b3a129",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.482782363891602, 'eval_accuracy': 0.6207482993197279, 'eval_f1': 0.6233347480319061, 'eval_precision': 0.8108960881073339, 'eval_recall': 0.5999664720807305, 'eval_runtime': 30.0674, 'eval_samples_per_second': 136.893, 'eval_steps_per_second': 4.29, 'epoch': 0.78}\n",
"{'loss': 4.5651, 'grad_norm': 0.8578382134437561, 'learning_rate': 4.4500000000000004e-05, 'epoch': 0.85}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "30b40f923e894e87b98cd86c2fe885e0",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.425670146942139, 'eval_accuracy': 0.6591350826044704, 'eval_f1': 0.6584699253003153, 'eval_precision': 0.8147592711787498, 'eval_recall': 0.6393439002306762, 'eval_runtime': 28.4304, 'eval_samples_per_second': 144.775, 'eval_steps_per_second': 4.537, 'epoch': 0.85}\n",
"{'loss': 4.5296, 'grad_norm': 0.9620392322540283, 'learning_rate': 4.4000000000000006e-05, 'epoch': 0.93}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "0a2e4094efc9460e8b0720746df15da2",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.364680290222168, 'eval_accuracy': 0.706268221574344, 'eval_f1': 0.7012054635300039, 'eval_precision': 0.8284350125904834, 'eval_recall': 0.688199507444556, 'eval_runtime': 28.5471, 'eval_samples_per_second': 144.183, 'eval_steps_per_second': 4.519, 'epoch': 0.93}\n",
"{'loss': 4.4911, 'grad_norm': 0.9173192977905273, 'learning_rate': 4.35e-05, 'epoch': 1.01}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "18ea4e46851043e9bd175bd132b7ed0f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.299846649169922, 'eval_accuracy': 0.7089407191448007, 'eval_f1': 0.7073568856764126, 'eval_precision': 0.8325596625698185, 'eval_recall': 0.6924090542708233, 'eval_runtime': 28.5965, 'eval_samples_per_second': 143.934, 'eval_steps_per_second': 4.511, 'epoch': 1.01}\n",
"{'loss': 4.4442, 'grad_norm': 0.9183776378631592, 'learning_rate': 4.3e-05, 'epoch': 1.09}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "f77e01f5212d46f49e8970bae34705be",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.228794574737549, 'eval_accuracy': 0.6938775510204082, 'eval_f1': 0.6890499178440211, 'eval_precision': 0.8302365826885487, 'eval_recall': 0.6758939664483897, 'eval_runtime': 28.7618, 'eval_samples_per_second': 143.106, 'eval_steps_per_second': 4.485, 'epoch': 1.09}\n",
"{'loss': 4.3912, 'grad_norm': 1.0323781967163086, 'learning_rate': 4.25e-05, 'epoch': 1.17}\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "12d209218a594953b4abfaf14de05b8b",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/129 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/andrewmayes/Openclassroom/CanineNet/env/lib/python3.12/site-packages/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n",
" _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'eval_loss': 4.152723789215088, 'eval_accuracy': 0.6873177842565598, 'eval_f1': 0.6863011851876918, 'eval_precision': 0.8261897457310591, 'eval_recall': 0.6702606718880093, 'eval_runtime': 29.7578, 'eval_samples_per_second': 138.317, 'eval_steps_per_second': 4.335, 'epoch': 1.17}\n"
]
}
],
"source": [
"metrics = {metric: evaluate.load(metric) for metric in METRICS}\n",
"\n",
"\n",
"# for lr in [5e-3, 5e-4, 5e-5]: # 5e-5\n",
"# for batch in [64]: # 32\n",
"# for model_name in [\"google/vit-base-patch16-224\", \"microsoft/swinv2-base-patch4-window16-256\", \"google/siglip-base-patch16-224\"]: # \"facebook/dinov2-base\"\n",
"\n",
"lr = 5e-4\n",
"batch = 32\n",
"model_name = \"microsoft/resnet-50\"\n",
"\n",
"image_processor = AutoImageProcessor.from_pretrained(model_name)\n",
"model = AutoModelForImageClassification.from_pretrained(\n",
"model_name,\n",
"num_labels=len(label2int),\n",
"id2label=int2label,\n",
"label2id=label2int,\n",
"ignore_mismatched_sizes=True,\n",
")\n",
"\n",
"# Then, in your transformations:\n",
"def train_transform(examples, num_ops=10, magnitude=9, num_magnitude_bins=31):\n",
"\n",
" transformation = v2.Compose(\n",
" [\n",
" v2.RandAugment(\n",
" num_ops=num_ops,\n",
" magnitude=magnitude,\n",
" num_magnitude_bins=num_magnitude_bins,\n",
" )\n",
" ]\n",
" )\n",
" # Ensure each image has three dimensions (in this case, ensure it's RGB)\n",
" examples[\"pixel_values\"] = [\n",
" image.convert(\"RGB\") for image in examples[\"pixel_values\"]\n",
" ]\n",
" # Apply transformations\n",
" examples[\"pixel_values\"] = [\n",
" image_processor(transformation(image), return_tensors=\"pt\")[\n",
" \"pixel_values\"\n",
" ].squeeze()\n",
" for image in examples[\"pixel_values\"]\n",
" ]\n",
" return examples\n",
"\n",
"\n",
"def test_transform(examples):\n",
" # Ensure each image is RGB\n",
" examples[\"pixel_values\"] = [\n",
" image.convert(\"RGB\") for image in examples[\"pixel_values\"]\n",
" ]\n",
" # Apply processing\n",
" examples[\"pixel_values\"] = [\n",
" image_processor(image, return_tensors=\"pt\")[\"pixel_values\"].squeeze()\n",
" for image in examples[\"pixel_values\"]\n",
" ]\n",
" return examples\n",
"\n",
"\n",
"def compute_metrics(eval_pred):\n",
" predictions, labels = eval_pred\n",
" # predictions = np.argmax(logits, axis=-1)\n",
" results = {}\n",
" for key, val in metrics.items():\n",
" if \"accuracy\" == key:\n",
" result = next(\n",
" iter(val.compute(predictions=predictions, references=labels).items())\n",
" )\n",
" if \"accuracy\" != key:\n",
" result = next(\n",
" iter(\n",
" val.compute(\n",
" predictions=predictions, references=labels, average=\"macro\"\n",
" ).items()\n",
" )\n",
" )\n",
" results[result[0]] = result[1]\n",
" return results\n",
"\n",
"\n",
"def collate_fn(examples):\n",
" pixel_values = torch.stack([example[\"pixel_values\"] for example in examples])\n",
" labels = torch.tensor([example[\"label\"] for example in examples])\n",
" return {\"pixel_values\": pixel_values, \"labels\": labels}\n",
"\n",
"\n",
"def preprocess_logits_for_metrics(logits, labels):\n",
" \"\"\"\n",
" Original Trainer may have a memory leak.\n",
" This is a workaround to avoid storing too many tensors that are not needed.\n",
" \"\"\"\n",
" pred_ids = torch.argmax(logits, dim=-1)\n",
" return pred_ids\n",
"\n",
"ds[\"train\"].set_transform(train_transform)\n",
"ds[\"test\"].set_transform(test_transform)\n",
"\n",
"training_args = TrainingArguments(**CONFIG[\"training_args\"])\n",
"training_args.per_device_train_batch_size = batch\n",
"training_args.per_device_eval_batch_size = batch\n",
"training_args.hub_model_id = f\"amaye15/{model_name.replace('/','-')}-batch{batch}-lr{lr}-standford-dogs\"\n",
"\n",
"mlflow.start_run(run_name=f\"{model_name.replace('/','-')}-batch{batch}-lr{lr}\")\n",
"\n",
"trainer = Trainer(\n",
" model=model,\n",
" args=training_args,\n",
" train_dataset=ds[\"train\"],\n",
" eval_dataset=ds[\"test\"],\n",
" tokenizer=image_processor,\n",
" data_collator=collate_fn,\n",
" compute_metrics=compute_metrics,\n",
" # callbacks=[early_stopping_callback],\n",
" preprocess_logits_for_metrics=preprocess_logits_for_metrics,\n",
")\n",
"\n",
"# Train the model\n",
"trainer.train()\n",
"\n",
"trainer.push_to_hub()\n",
"\n",
"mlflow.end_run()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "env",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|