diff --git a/03_pytorch_computer_vision.ipynb b/03_pytorch_computer_vision.ipynb index 7b0dbe9..3c0fc8a 100644 --- a/03_pytorch_computer_vision.ipynb +++ b/03_pytorch_computer_vision.ipynb @@ -1,4 +1,1393 @@ { + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "name": "03_pytorch_computer_vision.ipynb", + "provenance": [], + "authorship_tag": "ABX9TyM4UT6Sv8fKn4fF8Uzn3EyR", + "include_colab_link": true + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + }, + "widgets": { + "application/vnd.jupyter.widget-state+json": { + "c324c7c62f084db1bbaacc21382fced8": { + "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_ee5c491ce348497d94504efb50a953ca", + "IPY_MODEL_f64833c551c24df6ae9d7f902384f7f5", + "IPY_MODEL_5f907dce550f4b02bbe11a809d25809f" + ], + "layout": "IPY_MODEL_6620af85da2143b8a5917f8c12332b19" + } + }, + "ee5c491ce348497d94504efb50a953ca": { + "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_89dbb1bd104a4a14b7dfd922da581fa2", + "placeholder": "​", + "style": "IPY_MODEL_1abdfe17a6904f1f9638612c28c02128", + "value": "" + } + }, + "f64833c551c24df6ae9d7f902384f7f5": { + "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_91d947e3373447eab12e12d7504aa8f0", + "max": 26421880, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_27319eb6ac0c462bb0168491c3096f85", + "value": 26421880 + } + }, + "5f907dce550f4b02bbe11a809d25809f": { + "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_96d0639f212f46ab88a26bf8637d46b2", + "placeholder": "​", + "style": "IPY_MODEL_6a6ed3f6fc1741cda71abc200012eab9", + "value": " 26422272/? [00:01<00:00, 23407714.16it/s]" + } + }, + "6620af85da2143b8a5917f8c12332b19": { + "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 + } + }, + "89dbb1bd104a4a14b7dfd922da581fa2": { + "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 + } + }, + "1abdfe17a6904f1f9638612c28c02128": { + "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": "" + } + }, + "91d947e3373447eab12e12d7504aa8f0": { + "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 + } + }, + "27319eb6ac0c462bb0168491c3096f85": { + "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": "" + } + }, + "96d0639f212f46ab88a26bf8637d46b2": { + "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 + } + }, + "6a6ed3f6fc1741cda71abc200012eab9": { + "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": "" + } + }, + "229de989dfe1470e9b7dc87b95471d50": { + "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_7035607f089b4fb383bc1b29227b0158", + "IPY_MODEL_ffb9b116328e41a7b81dbb51bf33fa55", + "IPY_MODEL_f1980f36314140b5a10c5ac778b3d371" + ], + "layout": "IPY_MODEL_9e7f460e62c94d1db7ec1914c5cfbbb1" + } + }, + "7035607f089b4fb383bc1b29227b0158": { + "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_0a9d001f0d0b474c8ddfaae151b38f36", + "placeholder": "​", + "style": "IPY_MODEL_1d0e5b9f78194f698589223f6e27bd3a", + "value": "" + } + }, + "ffb9b116328e41a7b81dbb51bf33fa55": { + "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_f617dbc4556b49de961ac84f7c3e3fc7", + "max": 29515, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_a4d9940331ff4c5e837c5de2d0b9de66", + "value": 29515 + } + }, + "f1980f36314140b5a10c5ac778b3d371": { + "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_fa446cf9867f4543aff0a103e2ff23a1", + "placeholder": "​", + "style": "IPY_MODEL_a7ca5b963a8847298211a817cf16f673", + "value": " 29696/? [00:00<00:00, 133986.24it/s]" + } + }, + "9e7f460e62c94d1db7ec1914c5cfbbb1": { + "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 + } + }, + "0a9d001f0d0b474c8ddfaae151b38f36": { + "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 + } + }, + "1d0e5b9f78194f698589223f6e27bd3a": { + "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": "" + } + }, + "f617dbc4556b49de961ac84f7c3e3fc7": { + "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 + } + }, + "a4d9940331ff4c5e837c5de2d0b9de66": { + "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": "" + } + }, + "fa446cf9867f4543aff0a103e2ff23a1": { + "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 + } + }, + "a7ca5b963a8847298211a817cf16f673": { + "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": "" + } + }, + "ed2e4f7467414a39a422d1d7734e059e": { + "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_970676bd370e460fb15b787f69f2727b", + "IPY_MODEL_34f3459208134e40b8821b3bdff5ed80", + "IPY_MODEL_0a9dc6afa8de4475a9f74df8c5cf523a" + ], + "layout": "IPY_MODEL_0b3b37bc55394bf4a6155e3748319302" + } + }, + "970676bd370e460fb15b787f69f2727b": { + "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_1e1ce2c6c0014d86b930440fa78a7d2c", + "placeholder": "​", + "style": "IPY_MODEL_a20dd720d8f643b48993980d767df769", + "value": "" + } + }, + "34f3459208134e40b8821b3bdff5ed80": { + "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_792b67edd35e45a6b71500c6b7dd9dc6", + "max": 4422102, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_2b690ec71b8345f19fb5b35157a13689", + "value": 4422102 + } + }, + "0a9dc6afa8de4475a9f74df8c5cf523a": { + "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_9ffc17b4740e41359ed2133e80e63975", + "placeholder": "​", + "style": "IPY_MODEL_58e5a107952b4e10942a98b626de1a45", + "value": " 4422656/? [00:00<00:00, 5963200.80it/s]" + } + }, + "0b3b37bc55394bf4a6155e3748319302": { + "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 + } + }, + "1e1ce2c6c0014d86b930440fa78a7d2c": { + "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 + } + }, + "a20dd720d8f643b48993980d767df769": { + "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": "" + } + }, + "792b67edd35e45a6b71500c6b7dd9dc6": { + "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 + } + }, + "2b690ec71b8345f19fb5b35157a13689": { + "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": "" + } + }, + "9ffc17b4740e41359ed2133e80e63975": { + "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 + } + }, + "58e5a107952b4e10942a98b626de1a45": { + "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": "" + } + }, + "3207914733c4450c93562f48183c65c2": { + "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_8f5657a6b8d945b9ba304fbe475361f4", + "IPY_MODEL_19a61717ccb34a99b547f303a33f1b77", + "IPY_MODEL_7545091b13b348948392e70eda5d55ab" + ], + "layout": "IPY_MODEL_2ded7617a9a041e9a727adb81cbbc87b" + } + }, + "8f5657a6b8d945b9ba304fbe475361f4": { + "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_c0db4454c32d463da2beec1725d528ad", + "placeholder": "​", + "style": "IPY_MODEL_cc902d4aff3b4550aeb9696bd0979c31", + "value": "" + } + }, + "19a61717ccb34a99b547f303a33f1b77": { + "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_d2604e8301ab420bbe42f72190b47615", + "max": 5148, + "min": 0, + "orientation": "horizontal", + "style": "IPY_MODEL_6423756054194ed098c6625f70d293e8", + "value": 5148 + } + }, + "7545091b13b348948392e70eda5d55ab": { + "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_a65d9700959f408390e63954eeb9702a", + "placeholder": "​", + "style": "IPY_MODEL_e94d7413397440799aa29baffee3f0b8", + "value": " 6144/? [00:00<00:00, 97590.34it/s]" + } + }, + "2ded7617a9a041e9a727adb81cbbc87b": { + "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 + } + }, + "c0db4454c32d463da2beec1725d528ad": { + "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 + } + }, + "cc902d4aff3b4550aeb9696bd0979c31": { + "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": "" + } + }, + "d2604e8301ab420bbe42f72190b47615": { + "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 + } + }, + "6423756054194ed098c6625f70d293e8": { + "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": "" + } + }, + "a65d9700959f408390e63954eeb9702a": { + "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 + } + }, + "e94d7413397440799aa29baffee3f0b8": { + "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", @@ -12,9 +1401,6 @@ }, { "cell_type": "markdown", - "metadata": { - "id": "2f-BgWZ1or_f" - }, "source": [ "# (WIP) 03. PyTorch Computer Vision\n", "\n", @@ -67,13 +1453,13 @@ "| **9. Evaluating our best model** | Let's make some predictons on random images and evaluate our best model. |\n", "| **10. Making a confusion matrix** | A confusion matrix is a great way to evaluate a classification model, let's see how we can make one. |\n", "| **11. Saving and loading the best performing model** | Since we might want to use our model for later, let's save it and make sure it loads back in correctly. |" - ] + ], + "metadata": { + "id": "LN610wfhnD0h" + } }, { "cell_type": "markdown", - "metadata": { - "id": "SuWAAkAIor_h" - }, "source": [ "## Where can can you get help?\n", "\n", @@ -82,13 +1468,13 @@ "If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions) there too.\n", "\n", "And of course, there's the [PyTorch documentation](https://pytorch.org/docs/stable/index.html) and [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. " - ] + ], + "metadata": { + "id": "9ufraMiYnGAl" + } }, { "cell_type": "markdown", - "metadata": { - "id": "GLmjno1yor_h" - }, "source": [ "## 0. Computer vision libraries in PyTorch\n", "\n", @@ -106,17 +1492,20 @@ "> **Note:** The `torch.utils.data.Dataset` and `torch.utils.data.DataLoader` classes aren't only for computer vision in PyTorch, they are capable of dealing with many different types of data.\n", "\n", "Now we've covered some of the most important PyTorch computer vision libraries, let's import the relevant dependencies.\n" - ] + ], + "metadata": { + "id": "O2sfj9UjnJyO" + } }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "ZG6XbgBlor_i", - "outputId": "1dbaf673-8248-416a-f424-0d25fd0c4ec0" + "id": "FgQxblm0m-dc", + "outputId": "f8804360-3c18-49d1-aec3-8022a5849baa" }, "outputs": [ { @@ -148,9 +1537,6 @@ }, { "cell_type": "markdown", - "metadata": { - "id": "CEmuOrbQor_j" - }, "source": [ "## 1. Getting a dataset\n", "\n", @@ -183,65 +1569,86 @@ "* `target_transform` - you can transform the targets (labels) if you like too.\n", "\n", "Many other datasets in `torchvision` have these parameter options." - ] + ], + "metadata": { + "id": "bNDN7S5-nQEo" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Setup training data\n", + "train_data = datasets.FashionMNIST(\n", + " root=\"data\", # where to download data to?\n", + " train=True, # get training data\n", + " download=True, # download data if it doesn't exist on disk\n", + " transform=ToTensor(), # images come as PIL format, we want to turn into Torch tensors\n", + " target_transform=None # you can transform labels as well\n", + ")\n", + "\n", + "# Setup testing data\n", + "test_data = datasets.FashionMNIST(\n", + " root=\"data\",\n", + " train=False, # get test data\n", + " download=True,\n", + " transform=ToTensor()\n", + ")" + ], "metadata": { - "id": "wdAx9b7hor_j", "colab": { "base_uri": "https://localhost:8080/", - "height": 449, + "height": 450, "referenced_widgets": [ - "d50d98a1125f46b8b65fb2b449acd96e", - "2094dfdb5bd14ac891e5cef425dfd329", - "a8ecc18923c34dac9c1093fd85cbb868", - "4781f82f609c45d5a10c0ef818f0bb76", - "c754b71e73004a868a02efdf8d1d21d3", - "8e831509be094e5882823b4e3a15f0a0", - "01d7a9d34c65437d96ca669e81687660", - "bae8da49242b4cceb8159464c29013cd", - "88b938ecfd0b4cc4b110880b7cfb7345", - "219baa57cc3d487ebad585b06c07b60b", - "996cbcef273e458db293ea75692c9e6f", - "58466e448ff146448f567ad4ba2e6e3e", - "af8a7d76873d49118713c7ae465e2e2b", - "d05809c07e444fc8bb293d85a425d88c", - "c0f2c166727c4396af78815589d4aaf0", - "af7b864c2f7f46a6a6060c91f8e83f46", - "440039d25cf24fcabc4f1aba02c58635", - "1d5ab257e01548e69524500d06d96f35", - "7448045a0f1d4aa88f8503d25f27e9c3", - "994e98c3fa2e46d1a0fd6c645f5d9063", - "1a0a0b06dfed4bb7a9e4018cb34e88cb", - "69e43fbc68ec48638d3d69c6011c77d3", - "65d678adc1474588aec5a4947243253c", - "bf0b5d02f6bc42e5982d0b9907db64ac", - "57183f64a73c48e09a9fa074a3241915", - "88ccc3f41c8b4376bc7e516b07ea2ff8", - "83307872463a467d94720a5adc427462", - "59178ca370904a83a541094be2563f2b", - "14587717428d4fb188cdcfee568aca32", - "822b9344a395424dad8684444a2652b4", - "bc788a325b6a48c4b9a9244f3d445bd9", - "9f5fcd97bb37427dbac6b08b9a642e4c", - "4ba5e09d67644570a998d46c91fee6e5", - "086515e7fc15426ca6553cfb725ae9e1", - "a5a9a9e212b748b294d14deea212bc6d", - "734be7e9020f4b9b9696307c2bb49cb0", - "c2188e86db34444bbb0a3dfbb00ede07", - "0cda8af7be434dc39bcee2e47d53b0a0", - "8e71a375c50a451190ef564944b1473a", - "b5190742ba724112a3e33f4bffe3a147", - "30fda1f0c54649ee82024edd390b2d1b", - "89cac25100544e81a64ebff4bd0c8bd4", - "7be9ba8caf0d4ce295d9fa13439bdd33", - "be7751bd631f446a9a0b8500a2173d77" + "c324c7c62f084db1bbaacc21382fced8", + "ee5c491ce348497d94504efb50a953ca", + "f64833c551c24df6ae9d7f902384f7f5", + "5f907dce550f4b02bbe11a809d25809f", + "6620af85da2143b8a5917f8c12332b19", + "89dbb1bd104a4a14b7dfd922da581fa2", + "1abdfe17a6904f1f9638612c28c02128", + "91d947e3373447eab12e12d7504aa8f0", + "27319eb6ac0c462bb0168491c3096f85", + "96d0639f212f46ab88a26bf8637d46b2", + "6a6ed3f6fc1741cda71abc200012eab9", + "229de989dfe1470e9b7dc87b95471d50", + "7035607f089b4fb383bc1b29227b0158", + "ffb9b116328e41a7b81dbb51bf33fa55", + "f1980f36314140b5a10c5ac778b3d371", + "9e7f460e62c94d1db7ec1914c5cfbbb1", + "0a9d001f0d0b474c8ddfaae151b38f36", + "1d0e5b9f78194f698589223f6e27bd3a", + "f617dbc4556b49de961ac84f7c3e3fc7", + "a4d9940331ff4c5e837c5de2d0b9de66", + "fa446cf9867f4543aff0a103e2ff23a1", + "a7ca5b963a8847298211a817cf16f673", + "ed2e4f7467414a39a422d1d7734e059e", + "970676bd370e460fb15b787f69f2727b", + "34f3459208134e40b8821b3bdff5ed80", + "0a9dc6afa8de4475a9f74df8c5cf523a", + "0b3b37bc55394bf4a6155e3748319302", + "1e1ce2c6c0014d86b930440fa78a7d2c", + "a20dd720d8f643b48993980d767df769", + "792b67edd35e45a6b71500c6b7dd9dc6", + "2b690ec71b8345f19fb5b35157a13689", + "9ffc17b4740e41359ed2133e80e63975", + "58e5a107952b4e10942a98b626de1a45", + "3207914733c4450c93562f48183c65c2", + "8f5657a6b8d945b9ba304fbe475361f4", + "19a61717ccb34a99b547f303a33f1b77", + "7545091b13b348948392e70eda5d55ab", + "2ded7617a9a041e9a727adb81cbbc87b", + "c0db4454c32d463da2beec1725d528ad", + "cc902d4aff3b4550aeb9696bd0979c31", + "d2604e8301ab420bbe42f72190b47615", + "6423756054194ed098c6625f70d293e8", + "a65d9700959f408390e63954eeb9702a", + "e94d7413397440799aa29baffee3f0b8" ] }, - "outputId": "7b41ca80-2e11-4a6e-d0d4-ac54474323eb" + "id": "eLNqVU7inPIy", + "outputId": "4f21012d-401f-4cdb-ba00-ebbc78800dd5" }, + "execution_count": 2, "outputs": [ { "output_type": "stream", @@ -260,7 +1667,7 @@ "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, - "model_id": "d50d98a1125f46b8b65fb2b449acd96e" + "model_id": "c324c7c62f084db1bbaacc21382fced8" } }, "metadata": {} @@ -284,7 +1691,7 @@ "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, - "model_id": "58466e448ff146448f567ad4ba2e6e3e" + "model_id": "229de989dfe1470e9b7dc87b95471d50" } }, "metadata": {} @@ -308,7 +1715,7 @@ "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, - "model_id": "65d678adc1474588aec5a4947243253c" + "model_id": "ed2e4f7467414a39a422d1d7734e059e" } }, "metadata": {} @@ -332,7 +1739,7 @@ "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, - "model_id": "086515e7fc15426ca6553cfb725ae9e1" + "model_id": "3207914733c4450c93562f48183c65c2" } }, "metadata": {} @@ -345,45 +1752,32 @@ "\n" ] } - ], - "source": [ - "# Setup training data\n", - "train_data = datasets.FashionMNIST(\n", - " root=\"data\", # where to download data to?\n", - " train=True, # get training data\n", - " download=True, # download data if it doesn't exist on disk\n", - " transform=ToTensor(), # images come as PIL format, we want to turn into Torch tensors\n", - " target_transform=None # you can transform labels as well\n", - ")\n", - "\n", - "# Setup testing data\n", - "test_data = datasets.FashionMNIST(\n", - " root=\"data\",\n", - " train=False, # get test data\n", - " download=True,\n", - " transform=ToTensor()\n", - ")" ] }, { "cell_type": "markdown", - "metadata": { - "id": "MIWG-Fyfor_j" - }, "source": [ "Let's check out the first sample of the training data." - ] + ], + "metadata": { + "id": "H-zrjm72nU7h" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# See first training sample\n", + "image, label = train_data[0]\n", + "image, label" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "VfsokhFRor_j", - "outputId": "6e77ce95-64f1-46de-e36c-5f12299e4d55" + "id": "v3Uc4fXEnTt1", + "outputId": "1976a25d-0778-4302-f150-02b59a327a9a" }, + "execution_count": 3, "outputs": [ { "output_type": "execute_result", @@ -504,38 +1898,37 @@ ] }, "metadata": {}, - "execution_count": 7 + "execution_count": 3 } - ], - "source": [ - "# See first training sample\n", - "image, label = train_data[0]\n", - "image, label" ] }, { "cell_type": "markdown", - "metadata": { - "id": "rJr59W8zor_k" - }, "source": [ "### 1.1 Input and output shapes of a computer vision model\n", "\n", "We've got a big tensor of values (the image) leading to a single value for the target (the label).\n", "\n", "Let's see the image shape." - ] + ], + "metadata": { + "id": "JbMn08hjnZPu" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# What's the shape of the image?\n", + "image.shape" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "0HZhicOIor_k", - "outputId": "d5003b12-323e-4bea-e945-269a8e685989" + "id": "x2_YpEAZnXBe", + "outputId": "fe6e2a04-2d75-4293-8f86-7b9dadd876eb" }, + "execution_count": 4, "outputs": [ { "output_type": "execute_result", @@ -545,19 +1938,12 @@ ] }, "metadata": {}, - "execution_count": 8 + "execution_count": 4 } - ], - "source": [ - "# What's the shape of the image?\n", - "image.shape" ] }, { "cell_type": "markdown", - "metadata": { - "id": "OOxugDVjor_k" - }, "source": [ "The shape of the image tensor is `[1, 28, 28]` or more specifically:\n", "\n", @@ -587,18 +1973,25 @@ "But keep it in mind for when you're working on larger image datasets and using convolutional neural networks (we'll see these later).\n", "\n", "Let's check out more shapes of our data." - ] + ], + "metadata": { + "id": "r1M1S30end-E" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# How many samples are there? \n", + "len(train_data.data), len(train_data.targets), len(test_data.data), len(test_data.targets)" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "A1H9p1gVor_k", - "outputId": "76955cf0-fcf4-4f33-b960-9cb0afa5a8de" + "id": "1qiEYcWjnc5X", + "outputId": "9e714f3e-801b-4c59-d149-91761500e404" }, + "execution_count": 5, "outputs": [ { "output_type": "execute_result", @@ -608,37 +2001,38 @@ ] }, "metadata": {}, - "execution_count": 9 + "execution_count": 5 } - ], - "source": [ - "# How many samples are there? \n", - "len(train_data.data), len(train_data.targets), len(test_data.data), len(test_data.targets)" ] }, { "cell_type": "markdown", - "metadata": { - "id": "Sj2g3zt3or_l" - }, "source": [ "So we've got 60,000 training samples and 10,000 testing samples.\n", "\n", "What classes are there?\n", "\n", "We can find these via the `.classes` attribute." - ] + ], + "metadata": { + "id": "NmxSGGBonihC" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# See classes\n", + "class_names = train_data.classes\n", + "class_names" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "erCcDpm4or_l", - "outputId": "5ca515f7-4432-4457-aba8-c37a947799ac" + "id": "YaPD7wV6nj_1", + "outputId": "63135fdf-f2d6-4da3-8705-c5af24932ea4" }, + "execution_count": 7, "outputs": [ { "output_type": "execute_result", @@ -657,20 +2051,12 @@ ] }, "metadata": {}, - "execution_count": 10 + "execution_count": 7 } - ], - "source": [ - "# See classes\n", - "class_names = train_data.classes\n", - "class_names" ] }, { "cell_type": "markdown", - "metadata": { - "id": "6AM2AblKor_l" - }, "source": [ "Sweet! It looks like we're dealing with 10 different kinds of clothes.\n", "\n", @@ -679,19 +2065,29 @@ "Let's get visual.\n", "\n", "### 1.2 Visualizing our data" - ] + ], + "metadata": { + "id": "CEKIBtJHnphC" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "import matplotlib.pyplot as plt\n", + "image, label = train_data[0]\n", + "print(f\"Image shape: {image.shape}\")\n", + "plt.imshow(image.squeeze()) # image shape is [1, 28, 28] (colour channels, height, width)\n", + "plt.title(label);" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", - "height": 299 + "height": 298 }, - "id": "D29Z_WrJor_l", - "outputId": "3e2257a3-9641-4cb3-fbdd-0dee1d3fbea4" + "id": "cFfQavCNnoxr", + "outputId": "6bb1f287-6add-4151-af75-6a52231e29fc" }, + "execution_count": 8, "outputs": [ { "output_type": "stream", @@ -712,35 +2108,32 @@ "needs_background": "light" } } - ], - "source": [ - "import matplotlib.pyplot as plt\n", - "image, label = train_data[0]\n", - "print(f\"Image shape: {image.shape}\")\n", - "plt.imshow(image.squeeze()) # image shape is [1, 28, 28] (colour channels, height, width)\n", - "plt.title(label);" ] }, { "cell_type": "markdown", - "metadata": { - "id": "Ma6TW-xsor_m" - }, "source": [ "We can turn the image into grayscale using the `cmap` parameter of `plt.imshow()`." - ] + ], + "metadata": { + "id": "cq7ex9B9nwYd" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "plt.imshow(image.squeeze(), cmap=\"gray\")\n", + "plt.title(class_names[label]);" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 281 }, - "id": "8EtSyijkor_m", - "outputId": "52193207-f387-4869-ee54-bbfc956c27f2" + "id": "pXISTkSVnsji", + "outputId": "a5c9d6b9-d123-4650-d6d8-47e0bd88f100" }, + "execution_count": 9, "outputs": [ { "output_type": "display_data", @@ -754,34 +2147,43 @@ "needs_background": "light" } } - ], - "source": [ - "plt.imshow(image.squeeze(), cmap=\"gray\")\n", - "plt.title(class_names[label]);" ] }, { "cell_type": "markdown", - "metadata": { - "id": "imhQh9Hvor_m" - }, "source": [ "Beautiful, well as beautiful as a pixelated grayscale ankle boot can get.\n", "\n", "Let's view a few more." - ] + ], + "metadata": { + "id": "VBZtjGuhnzqV" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Plot more images\n", + "torch.manual_seed(42)\n", + "fig = plt.figure(figsize=(9, 9))\n", + "rows, cols = 4, 4\n", + "for i in range(1, rows * cols + 1):\n", + " random_idx = torch.randint(0, len(train_data), size=[1]).item()\n", + " img, label = train_data[random_idx]\n", + " fig.add_subplot(rows, cols, i)\n", + " plt.imshow(img.squeeze(), cmap=\"gray\")\n", + " plt.title(class_names[label])\n", + " plt.axis(False);" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 536 }, - "id": "uPMHcKJlor_m", - "outputId": "0f448734-2f22-4ba5-ff34-6d4f059cdfa0" + "id": "56kfSNZqnyBv", + "outputId": "c917cd5e-f565-487d-8e84-7ff2dc9cbee9" }, + "execution_count": 10, "outputs": [ { "output_type": "display_data", @@ -795,26 +2197,10 @@ "needs_background": "light" } } - ], - "source": [ - "# Plot more images\n", - "torch.manual_seed(42)\n", - "fig = plt.figure(figsize=(9, 9))\n", - "rows, cols = 4, 4\n", - "for i in range(1, rows * cols + 1):\n", - " random_idx = torch.randint(0, len(train_data), size=[1]).item()\n", - " img, label = train_data[random_idx]\n", - " fig.add_subplot(rows, cols, i)\n", - " plt.imshow(img.squeeze(), cmap=\"gray\")\n", - " plt.title(class_names[label])\n", - " plt.axis(False);" ] }, { "cell_type": "markdown", - "metadata": { - "id": "Ou5mIkFDor_n" - }, "source": [ "Hmmm, this dataset doesn't look too aesthetic.\n", "\n", @@ -829,13 +2215,13 @@ "But I think coding a model in PyTorch would be faster.\n", "\n", "> **Question:** Do you think the above data can be model with only straight (linear) lines? Or do you think you'd also need non-straight (non-linear) lines?" - ] + ], + "metadata": { + "id": "zXeju8HKn2zR" + } }, { "cell_type": "markdown", - "metadata": { - "id": "yPkuYEu4or_n" - }, "source": [ "## TK - 2. Prepare DataLoader\n", "\n", @@ -871,29 +2257,13 @@ "*Batching FashionMNIST with a batch size of 32 and shuffle turned on. A similar batching process will occur for other datasets but will differ depending on the batch size.*\n", "\n", "Let's create `DataLoader`'s for our training and test sets. " - ] + ], + "metadata": { + "id": "Iz4RBQdSn7KI" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "1gHENhrAor_n", - "outputId": "2ec2eccf-b694-4d6d-87b8-e8d6f226dff0" - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Dataloaders: (, )\n", - "Length of train dataloader: 1875 batches of 32\n", - "Length of test dataloader: 313 batches of 32\n" - ] - } - ], "source": [ "from torch.utils.data import DataLoader\n", "\n", @@ -915,27 +2285,51 @@ "print(f\"Dataloaders: {train_dataloader, test_dataloader}\") \n", "print(f\"Length of train dataloader: {len(train_dataloader)} batches of {BATCH_SIZE}\")\n", "print(f\"Length of test dataloader: {len(test_dataloader)} batches of {BATCH_SIZE}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "IWhRPVnxor_o" - }, - "source": [ - "Since the `DataLoader`'s are Python iterables, we can check out what's inside using `next(iter(dataloader))`." - ] - }, - { - "cell_type": "code", - "execution_count": null, + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "urAOd6pVor_o", - "outputId": "ab216860-d6a9-4837-bee0-1e8351b502c8" + "id": "sBuS99vwn1Zj", + "outputId": "2d3ebf65-f5b6-49fd-bfaa-d5ad59b65241" }, + "execution_count": 11, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Dataloaders: (, )\n", + "Length of train dataloader: 1875 batches of 32\n", + "Length of test dataloader: 313 batches of 32\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Since the `DataLoader`'s are Python iterables, we can check out what's inside using `next(iter(dataloader))`." + ], + "metadata": { + "id": "Cs5cbkBCn-9r" + } + }, + { + "cell_type": "code", + "source": [ + "# Check out what's inside the training dataloader\n", + "train_features_batch, train_labels_batch = next(iter(train_dataloader))\n", + "train_features_batch.shape, train_labels_batch.shape" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "5n_avEfdn95y", + "outputId": "51f80005-37eb-4a1d-a4e9-72f329d4d491" + }, + "execution_count": 12, "outputs": [ { "output_type": "execute_result", @@ -945,35 +2339,41 @@ ] }, "metadata": {}, - "execution_count": 15 + "execution_count": 12 } - ], - "source": [ - "# Check out what's inside the training dataloader\n", - "train_features_batch, train_labels_batch = next(iter(train_dataloader))\n", - "train_features_batch.shape, train_labels_batch.shape" ] }, { "cell_type": "markdown", - "metadata": { - "id": "To07Swo2or_o" - }, "source": [ "And we can see that the data remains unchanged by checking a single sample. " - ] + ], + "metadata": { + "id": "cjYDKpxSoDW3" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Show a sample\n", + "torch.manual_seed(42)\n", + "random_idx = torch.randint(0, len(train_features_batch), size=[1]).item()\n", + "img, label = train_features_batch[random_idx], train_labels_batch[random_idx]\n", + "plt.imshow(img.squeeze(), cmap=\"gray\")\n", + "plt.title(class_names[label])\n", + "plt.axis(\"Off\");\n", + "print(f\"Image size: {img.shape}\")\n", + "print(f\"Label: {label}, label size: {label.shape}\")" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 299 }, - "id": "7rbU3vl0or_o", - "outputId": "e99cab26-d2eb-40b9-a399-b01f564929e3" + "id": "TEDUXasFoB8g", + "outputId": "0bb8e593-0d83-4f3c-91cf-29613d45081f" }, + "execution_count": 13, "outputs": [ { "output_type": "stream", @@ -995,24 +2395,10 @@ "needs_background": "light" } } - ], - "source": [ - "# Show a sample\n", - "torch.manual_seed(42)\n", - "random_idx = torch.randint(0, len(train_features_batch), size=[1]).item()\n", - "img, label = train_features_batch[random_idx], train_labels_batch[random_idx]\n", - "plt.imshow(img.squeeze(), cmap=\"gray\")\n", - "plt.title(class_names[label])\n", - "plt.axis(\"Off\");\n", - "print(f\"Image size: {img.shape}\")\n", - "print(f\"Label: {label}, label size: {label.shape}\")" ] }, { "cell_type": "markdown", - "metadata": { - "id": "aZtQhMTlor_o" - }, "source": [ "## TK - 3. Model 0: Build a baseline model\n", "\n", @@ -1035,28 +2421,13 @@ "`nn.Flatten()` compresses the dimensions of a tensor into a single vector.\n", "\n", "This is easier to understand when you see it." - ] + ], + "metadata": { + "id": "ZFE2uFRDoHTB" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "v5ew78U4or_p", - "outputId": "25e26279-3556-4fa6-9c7c-56e15f5c4be3" - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Shape before flattening: torch.Size([1, 28, 28]) -> [color_channels, height, width]\n", - "Shape after flattening: torch.Size([1, 784]) -> [color_channels, height*width]\n" - ] - } - ], "source": [ "# Create a flatten layer\n", "flatten_model = nn.Flatten() # all nn modules function as a model (can do a forward pass)\n", @@ -1074,32 +2445,45 @@ "# Try uncommenting below and see what happened\n", "#print(x)\n", "#print(output)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "jJNgcNnpoEqg", + "outputId": "a4559d51-511c-45e5-a866-eb05e74cd39f" + }, + "execution_count": 14, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Shape before flattening: torch.Size([1, 28, 28]) -> [color_channels, height, width]\n", + "Shape after flattening: torch.Size([1, 784]) -> [color_channels, height*width]\n" + ] + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "CrUOh0Vior_p" - }, "source": [ "The `nn.Flatten()` layer took our shape from `[color_channels, height, width]` to `[color_channels, height*width]`.\n", "\n", "Why do this?\n", "\n", - "Because we've now turned our pixel data from height and width dimensions into one long **feature vector**.\n", + "Because we've now turned our pixel data from height and width dimensions into one long **feature vector** (`[1, 28, 28]` -> `[1, 784]`).\n", "\n", "And `nn.Linear()` layers like their inputs to be in the form of feature vectors.\n", "\n", "Let's create our first model using `nn.Flatten()` as the first layer. " - ] + ], + "metadata": { + "id": "3gJ4ptg0oLjn" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "QSec-LH0or_p" - }, - "outputs": [], "source": [ "from torch import nn\n", "class FashionMNISTModelV0(nn.Module):\n", @@ -1113,13 +2497,15 @@ " \n", " def forward(self, x):\n", " return self.layer_stack(x)" - ] + ], + "metadata": { + "id": "OuLZTUTXoJeu" + }, + "execution_count": 15, + "outputs": [] }, { "cell_type": "markdown", - "metadata": { - "id": "RVOqlWDgor_p" - }, "source": [ "Wonderful!\n", "\n", @@ -1131,18 +2517,31 @@ "* `output_shape=len(class_names)` - since we're working with a multi-class classification problem, we need an output neuron per class in our dataset.\n", "\n", "Let's create an instance of our model and send to the CPU for now (we'll run a small test for CPU vs. GPU soon)." - ] + ], + "metadata": { + "id": "a9vELss1odle" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "torch.manual_seed(42)\n", + "\n", + "# Need to setup model with input parameters\n", + "model_0 = FashionMNISTModelV0(input_shape=784, # one for every pixel (28x28)\n", + " hidden_units=10, # how many units in the hiden layer\n", + " output_shape=len(class_names) # one for every class\n", + ")\n", + "model_0.to(\"cpu\") # keep model on CPU to begin wtih " + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "ytJAxA2Qor_p", - "outputId": "928a94b5-5483-4880-e048-d4c42df222e5" + "id": "2qqwt2C7obmp", + "outputId": "eb7fe716-577a-4ee3-9b39-c56aa1a7358d" }, + "execution_count": 16, "outputs": [ { "output_type": "execute_result", @@ -1158,52 +2557,25 @@ ] }, "metadata": {}, - "execution_count": 19 + "execution_count": 16 } - ], - "source": [ - "torch.manual_seed(42)\n", - "\n", - "# Need to setup model with input parameters\n", - "model_0 = FashionMNISTModelV0(input_shape=784, # one for every pixel (28x28)\n", - " hidden_units=10, # how many units in the hiden layer\n", - " output_shape=len(class_names) # one for every class\n", - ")\n", - "model_0.to(\"cpu\") # keep model on CPU to begin wtih " ] }, { "cell_type": "markdown", - "metadata": { - "id": "LFBpo7V7or_p" - }, "source": [ "### TK - 3.1 Setup loss, optimizer and evaluation metrics for Model 1\n", "\n", "Since we're working on a classification problem, let's bring in our [`helper_functions.py` script](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) and subsequently the `accuracy_fn()` we defined in [notebook 02](https://www.learnpytorch.io/02_pytorch_classification/).\n", "\n", "> **Note:** Rather than importing and using our own accuracy function or evaluation metric(s), you could import various evaluation metrics from the [TorchMetrics package](https://torchmetrics.readthedocs.io/en/latest/)." - ] + ], + "metadata": { + "id": "ilMTlyoFog6_" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "QocEcVZkor_q", - "outputId": "fea1a5cb-0186-4491-e333-d6286a967f9c" - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Downloading helper_functions.py\n" - ] - } - ], "source": [ "import requests\n", "from pathlib import Path \n", @@ -1217,28 +2589,40 @@ " request = requests.get(\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py\")\n", " with open(\"helper_functions.py\", \"wb\") as f:\n", " f.write(request.content)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "PDa-azArogUc", + "outputId": "be7c4d74-a187-40a1-cb01-0c462a876775" + }, + "execution_count": 17, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Downloading helper_functions.py\n" + ] + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "A5L3j8NWor_q" - }, "source": [ "Now we've got the `helper_functions.py` file, let's import `accuracy_fn()` as well as setup a loss function and an optimizer.\n", "\n", "Since we're working with a multi-class classification problem, we'll use [`nn.CrossEntropyLoss()`](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) as the loss function.\n", "\n", "And we'll setup [`torch.optim.SGD()`](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html) as the optimizer with a learning rate of `0.1`." - ] + ], + "metadata": { + "id": "LsRrsIiookNN" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "QHSuQlm_or_q" - }, - "outputs": [], "source": [ "# Import accuracy metric\n", "from helper_functions import accuracy_fn # Note: could also use torchmetrics.Accuracy()\n", @@ -1246,13 +2630,15 @@ "# Setup loss function and optimizer\n", "loss_fn = nn.CrossEntropyLoss() # this is also called \"criterion\"/\"cost function\" in some places\n", "optimizer = torch.optim.SGD(params=model_0.parameters(), lr=0.1)" - ] + ], + "metadata": { + "id": "tHDZiLcYofOp" + }, + "execution_count": 18, + "outputs": [] }, { "cell_type": "markdown", - "metadata": { - "id": "gmdhD7ILor_r" - }, "source": [ "### 3.2 Creating a function to time our experiments\n", "\n", @@ -1267,15 +2653,13 @@ "We'll train this model on the CPU but the next one on the CPU and see what happens.\n", "\n", "Our timing function will import the [`timeit.default_timer()` function](https://docs.python.org/3/library/timeit.html#timeit.default_timer) from the Python [`timeit` module](https://docs.python.org/3/library/timeit.html)." - ] + ], + "metadata": { + "id": "YkpUE9azonry" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "83R8P1lior_s" - }, - "outputs": [], "source": [ "from timeit import default_timer as timer \n", "def print_train_time(start, end, device=None):\n", @@ -1292,13 +2676,15 @@ " total_time = end - start\n", " print(f\"Train time on {device}: {total_time:.3f} seconds\")\n", " return total_time" - ] + ], + "metadata": { + "id": "7SyTluBRomV6" + }, + "execution_count": 19, + "outputs": [] }, { "cell_type": "markdown", - "metadata": { - "id": "vNiKK02tor_s" - }, "source": [ "### 3.3 Creating a training loop and training a model on batches of data\n", "\n", @@ -1328,57 +2714,13 @@ "A fair few steps but...\n", "\n", "...if in doubt, code it out. " - ] + ], + "metadata": { + "id": "JcEtQjvJor6o" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "vS5MRb_0or_t", - "outputId": "39df5192-51c2-4c5e-bd15-0d49b9cc70b1" - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Epoch: 0\n", - "-------\n", - "Looked at 0/60000 samples\n", - "Looked at 12800/60000 samples\n", - "Looked at 25600/60000 samples\n", - "Looked at 38400/60000 samples\n", - "Looked at 51200/60000 samples\n", - "\n", - "Train loss: 0.59039 | Test loss: 0.50954, Test acc: 82.04%\n", - "\n", - "Epoch: 1\n", - "-------\n", - "Looked at 0/60000 samples\n", - "Looked at 12800/60000 samples\n", - "Looked at 25600/60000 samples\n", - "Looked at 38400/60000 samples\n", - "Looked at 51200/60000 samples\n", - "\n", - "Train loss: 0.47633 | Test loss: 0.47989, Test acc: 83.20%\n", - "\n", - "Epoch: 2\n", - "-------\n", - "Looked at 0/60000 samples\n", - "Looked at 12800/60000 samples\n", - "Looked at 25600/60000 samples\n", - "Looked at 38400/60000 samples\n", - "Looked at 51200/60000 samples\n", - "\n", - "Train loss: 0.45503 | Test loss: 0.47664, Test acc: 83.43%\n", - "\n", - "Train time on cpu: 28.428 seconds\n" - ] - } - ], "source": [ "# Set the seed and start the timer\n", "torch.manual_seed(42)\n", @@ -1448,26 +2790,70 @@ "total_train_time_model_0 = print_train_time(start=train_time_start_on_cpu, \n", " end=train_time_end_on_cpu,\n", " device=str(next(model_0.parameters()).device))" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "naT1ATbQoqFV", + "outputId": "8357d701-f824-49d1-ec69-8d22fe715491" + }, + "execution_count": 20, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Epoch: 0\n", + "-------\n", + "Looked at 0/60000 samples\n", + "Looked at 12800/60000 samples\n", + "Looked at 25600/60000 samples\n", + "Looked at 38400/60000 samples\n", + "Looked at 51200/60000 samples\n", + "\n", + "Train loss: 0.59039 | Test loss: 0.50954, Test acc: 82.04%\n", + "\n", + "Epoch: 1\n", + "-------\n", + "Looked at 0/60000 samples\n", + "Looked at 12800/60000 samples\n", + "Looked at 25600/60000 samples\n", + "Looked at 38400/60000 samples\n", + "Looked at 51200/60000 samples\n", + "\n", + "Train loss: 0.47633 | Test loss: 0.47989, Test acc: 83.20%\n", + "\n", + "Epoch: 2\n", + "-------\n", + "Looked at 0/60000 samples\n", + "Looked at 12800/60000 samples\n", + "Looked at 25600/60000 samples\n", + "Looked at 38400/60000 samples\n", + "Looked at 51200/60000 samples\n", + "\n", + "Train loss: 0.45503 | Test loss: 0.47664, Test acc: 83.43%\n", + "\n", + "Train time on cpu: 34.323 seconds\n" + ] + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "buywnKoEor_t" - }, "source": [ "Nice! Looks like our baseline model did fairly well.\n", "\n", "It didn't take too long to train either, even just on the CPU, I wonder if it'll speed up on the GPU?\n", "\n", "Let's write some code to evaluate our model." - ] + ], + "metadata": { + "id": "WME-Yocxowgs" + } }, { "cell_type": "markdown", - "metadata": { - "id": "XPaPhAukor_t" - }, "source": [ "## TK - 4. Make predictions and get Model 0 results\n", "\n", @@ -1476,32 +2862,13 @@ "Namely, let's create a function that takes in a trained model, a `DataLoader`, a loss function and an accuracy function.\n", "\n", "The function will use the model to make predictions on the data in the `DataLoader` and then we can evaluate those predictions using the loss function and accuracy function." - ] + ], + "metadata": { + "id": "OzmgukBnoyqJ" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "p7Xe29OUor_t", - "outputId": "59d47299-a4e1-464b-f11b-934e1d3a8ca5" - }, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "{'model_acc': 83.42651757188499,\n", - " 'model_loss': 0.47663888335227966,\n", - " 'model_name': 'FashionMNISTModelV0'}" - ] - }, - "metadata": {}, - "execution_count": 24 - } - ], "source": [ "torch.manual_seed(42)\n", "def eval_model(model: torch.nn.Module, \n", @@ -1544,24 +2911,43 @@ " loss_fn=loss_fn, accuracy_fn=accuracy_fn\n", ")\n", "model_0_results" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "BXESm9YWouCH", + "outputId": "f0e552b4-1280-41e5-adfe-6795b0c386de" + }, + "execution_count": 21, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'model_acc': 83.42651757188499,\n", + " 'model_loss': 0.47663888335227966,\n", + " 'model_name': 'FashionMNISTModelV0'}" + ] + }, + "metadata": {}, + "execution_count": 21 + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "FcJukKh4or_u" - }, "source": [ "Looking good!\n", "\n", "We can use this dictionary to compare the baseline model results to other models later on." - ] + ], + "metadata": { + "id": "ro5n7EMMo3Am" + } }, { "cell_type": "markdown", - "metadata": { - "id": "3tG3-gvEor_u" - }, "source": [ "## TK 5. Setup device agnostic-code (for using a GPU if there is one)\n", "We've seen how long it takes to train ma PyTorch model on 60,000 samples on CPU.\n", @@ -1571,57 +2957,57 @@ "Now let's setup some [device-agnostic code](https://pytorch.org/docs/stable/notes/cuda.html#best-practices) for our models and data to run on GPU if it's available.\n", "\n", "If you're running this notebook on Google Colab, and you don't a GPU turned on yet, it's now time to turn one on via `Runtime -> Change runtime type -> Hardware accelerator -> GPU`. If you do this, your runtime will likely reset and you'll have to run all of the cells above by going `Runtime -> Run before`." - ] + ], + "metadata": { + "id": "RFFkETpoo45M" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Setup device agnostic code\n", + "import torch\n", + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "device" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, - "id": "zKCwdr2oor_u", - "outputId": "6424a2e6-88a4-4c16-fe3f-11d3001a7ad5" + "id": "g5yss0Dvo1JA", + "outputId": "3a890b1e-a6d4-43f0-a25f-399de45aa463" }, + "execution_count": 22, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ - "'cuda'" + "'cpu'" ], "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" } }, "metadata": {}, - "execution_count": 25 + "execution_count": 22 } - ], - "source": [ - "# Setup device agnostic code\n", - "import torch\n", - "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", - "device" ] }, { "cell_type": "markdown", - "metadata": { - "id": "1YMZ8okWor_v" - }, "source": [ "Beautiful!\n", "\n", "Let's build another model." - ] + ], + "metadata": { + "id": "qAhkMuvdo8T1" + } }, { "cell_type": "markdown", - "metadata": { - "id": "C_OJ5onmor_v" - }, "source": [ "## TK - 6. Model 1: Building a better model with non-linearity\n", "\n", @@ -1634,15 +3020,13 @@ "Let's find out.\n", "\n", "We'll do so by recreating a similar model to before, except this time we'll put non-linear functions (`nn.ReLU()`) in between each linear layer." - ] + ], + "metadata": { + "id": "23Oy8YbSo9G_" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "Wlyv5qPjor_v" - }, - "outputs": [], "source": [ "# Create a model with non-linear and linear layers\n", "class FashionMNISTModelV1(nn.Module):\n", @@ -1658,13 +3042,15 @@ " \n", " def forward(self, x):\n", " return self.layer_stack(x)" - ] + ], + "metadata": { + "id": "YuGtaWSSo6XV" + }, + "execution_count": 23, + "outputs": [] }, { "cell_type": "markdown", - "metadata": { - "id": "R335kDQCor_v" - }, "source": [ "That looks good.\n", "\n", @@ -1673,30 +3059,13 @@ "We'll need `input_shape=784` (equal to the number of features of our image data), `hidden_units=10` (starting small and the same as our baseline model) and `output_shape=len(class_names)` (one output unit per class).\n", "\n", "> **Note:** Notice how we kept most of the settings of our model the same except for one change: adding non-linear layers. This is a standard practice for running a series of machine learning experiments, change one thing and see what happens, then do it again, again, again." - ] + ], + "metadata": { + "id": "568fkJc-pBQN" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "jJIv2sHOor_v", - "outputId": "0553d25e-bba6-4c4b-bddd-1f565e9c8297" - }, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "device(type='cuda', index=0)" - ] - }, - "metadata": {}, - "execution_count": 27 - } - ], "source": [ "torch.manual_seed(42)\n", "model_1 = FashionMNISTModelV1(input_shape=784, # number of input features\n", @@ -1704,38 +3073,55 @@ " output_shape=len(class_names) # number of output classes desired\n", ").to(device) # send model to GPU if it's available\n", "next(model_1.parameters()).device # check model device" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "IJ0kDOc5pDLk", + "outputId": "4a673d47-0f5f-417c-ed6b-d9e610164d1a" + }, + "execution_count": 24, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "device(type='cpu')" + ] + }, + "metadata": {}, + "execution_count": 24 + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "XY0APfb6or_w" - }, "source": [ "### TK - 6.1 Setup loss, optimizer and evaluation metrics\n", "\n", "As usual, we'll setup a loss function, an optimizer and an evaluation metric (we could do multiple evaluation metrics but we'll stick with accuracy for now)." - ] + ], + "metadata": { + "id": "RWhlOf3PpF7D" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "1rbmn5y2or_w" - }, - "outputs": [], "source": [ "from helper_functions import accuracy_fn\n", "loss_fn = nn.CrossEntropyLoss()\n", "optimizer = torch.optim.SGD(params=model_1.parameters(), \n", " lr=0.1)" - ] + ], + "metadata": { + "id": "J5sLGFqJpElO" + }, + "execution_count": 25, + "outputs": [] }, { "cell_type": "markdown", - "metadata": { - "id": "ay7wYJVLor_w" - }, "source": [ "### TK - 6.2 Functionizing training and test loops\n", "\n", @@ -1750,15 +3136,13 @@ "The testing loop will be similar but it'll be called `test_step()` and it'll take in a model, a `DataLoader`, a loss function and an evaluation function.\n", "\n", "> **Note:** Since these are functions, you can customize them in any way you like. What we're making here can be considered barebones training and testing functions for our specific classification use case." - ] + ], + "metadata": { + "id": "9jIQEcdXpINg" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "a9BktNPhor_w" - }, - "outputs": [], "source": [ "def train_step(model, data_loader, loss_fn, optimizer, accuracy_fn, device=device):\n", " train_loss, train_acc = 0, 0\n", @@ -1811,13 +3195,15 @@ " test_loss /= len(data_loader)\n", " test_acc /= len(data_loader)\n", " print(f\"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\\n\")" - ] + ], + "metadata": { + "id": "ztWoQzdLpHGn" + }, + "execution_count": 26, + "outputs": [] }, { "cell_type": "markdown", - "metadata": { - "id": "FOZ7tMQ1or_w" - }, "source": [ "Woohoo!\n", "\n", @@ -1830,42 +3216,13 @@ "> **Note:** You can customize how often you do a testing step. Sometimes people do them every five epochs or 10 epochs or in our case, every epoch.\n", "\n", "Let's also time things to see how long our code takes to run on the GPU." - ] + ], + "metadata": { + "id": "mAX25W6LpLRg" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "Lii2Xxbpor_w", - "outputId": "c56315b2-3160-46f7-da2c-e1c6b3428e76" - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Epoch: 0\n", - "---------\n", - "Train loss: 0.47664 | Train accuracy: 83.43%\n", - "Test loss: 0.95636 | Test accuracy: 65.00%\n", - "\n", - "Epoch: 1\n", - "---------\n", - "Train loss: 0.47664 | Train accuracy: 83.43%\n", - "Test loss: 0.72227 | Test accuracy: 73.91%\n", - "\n", - "Epoch: 2\n", - "---------\n", - "Train loss: 0.47664 | Train accuracy: 83.43%\n", - "Test loss: 0.68500 | Test accuracy: 75.02%\n", - "\n", - "Train time on cuda: 32.483 seconds\n" - ] - } - ], "source": [ "torch.manual_seed(42)\n", "\n", @@ -1892,13 +3249,42 @@ "total_train_time_model_1 = print_train_time(start=train_time_start_on_gpu,\n", " end=train_time_end_on_gpu,\n", " device=device)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "9dGWNmL1pJ08", + "outputId": "717fb13d-b6c6-48da-eb81-fbb845316b49" + }, + "execution_count": 27, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Epoch: 0\n", + "---------\n", + "Train loss: 0.47664 | Train accuracy: 83.43%\n", + "Test loss: 0.95636 | Test accuracy: 65.00%\n", + "\n", + "Epoch: 1\n", + "---------\n", + "Train loss: 0.47664 | Train accuracy: 83.43%\n", + "Test loss: 0.72227 | Test accuracy: 73.91%\n", + "\n", + "Epoch: 2\n", + "---------\n", + "Train loss: 0.47664 | Train accuracy: 83.43%\n", + "Test loss: 0.68500 | Test accuracy: 75.02%\n", + "\n", + "Train time on cpu: 33.530 seconds\n" + ] + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "khOHQvBIor_w" - }, "source": [ "Excellent!\n", "\n", @@ -1919,40 +3305,13 @@ "> However, this is largely dependant on the hardware you're using. With practice, you will get used to where the best place to train your models is. \n", "\n", "Let's evaluate our trained `model_1` using our `eval_model()` function and see how it went." - ] + ], + "metadata": { + "id": "S7R0_49spOFI" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/", - "height": 458 - }, - "id": "HMjUbyfyor_w", - "outputId": "628cd344-6767-4179-af12-5c05d54d7adb" - }, - "outputs": [ - { - "output_type": "error", - "ename": "RuntimeError", - "evalue": "ignored", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mdata_loader\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtest_dataloader\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mloss_fn\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mloss_fn\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m accuracy_fn=accuracy_fn) # will error due to `eval_model()` not using device agnostic code \n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0mmodel_1_results\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m\u001b[0m in \u001b[0;36meval_model\u001b[0;34m(model, data_loader, loss_fn, accuracy_fn)\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdata_loader\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;31m# Make predictions with the model\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 22\u001b[0;31m \u001b[0my_pred\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 23\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 24\u001b[0m \u001b[0;31m# Accumulate the loss and accuracy values per batch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1100\u001b[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks\n\u001b[1;32m 1101\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1102\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1103\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1104\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 14\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlayer_stack\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1100\u001b[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks\n\u001b[1;32m 1101\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1102\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1103\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1104\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/container.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 139\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 140\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mmodule\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 141\u001b[0;31m \u001b[0minput\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodule\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 142\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 143\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1100\u001b[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks\n\u001b[1;32m 1101\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1102\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1103\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1104\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/linear.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 101\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 102\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 103\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mF\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinear\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 104\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 105\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mextra_repr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py\u001b[0m in \u001b[0;36mlinear\u001b[0;34m(input, weight, bias)\u001b[0m\n\u001b[1;32m 1846\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mhas_torch_function_variadic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1847\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mhandle_torch_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlinear\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbias\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1848\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_C\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_nn\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinear\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1849\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1850\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mRuntimeError\u001b[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)" - ] - } - ], "source": [ "torch.manual_seed(42)\n", "\n", @@ -1962,13 +3321,32 @@ " loss_fn=loss_fn, \n", " accuracy_fn=accuracy_fn) # will error due to `eval_model()` not using device agnostic code \n", "model_1_results " + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "hl90HIyrpMmf", + "outputId": "d74522f5-2efa-40a8-c64c-80e61f3b8e25" + }, + "execution_count": 28, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'model_acc': 75.01996805111821,\n", + " 'model_loss': 0.6850008368492126,\n", + " 'model_name': 'FashionMNISTModelV1'}" + ] + }, + "metadata": {}, + "execution_count": 28 + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "ssMnlqjkor_w" - }, "source": [ "Oh no! \n", "\n", @@ -1983,15 +3361,13 @@ "How about we fix that by passing a target `device` parameter to our `eval_model()` function?\n", "\n", "Then we'll try calculating the results again." - ] + ], + "metadata": { + "id": "1sOHeJmkpRPP" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "nisdJXTZor_w" - }, - "outputs": [], "source": [ "# Move values to device\n", "torch.manual_seed(42)\n", @@ -2035,25 +3411,61 @@ " device=device\n", ")\n", "model_1_results" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "unnWF9IGpSSQ", + "outputId": "ecae61f0-f186-4cca-a0bc-c2c2e67921b3" + }, + "execution_count": 29, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'model_acc': 75.01996805111821,\n", + " 'model_loss': 0.6850008368492126,\n", + " 'model_name': 'FashionMNISTModelV1'}" + ] + }, + "metadata": {}, + "execution_count": 29 + } ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "dzNbpJR4or_x" - }, - "outputs": [], "source": [ "# Check baseline results\n", "model_0_results" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "mwjHSiPYpUIR", + "outputId": "b55eab45-728b-4b50-b5a0-8db5ccd1e1f5" + }, + "execution_count": 30, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'model_acc': 83.42651757188499,\n", + " 'model_loss': 0.47663888335227966,\n", + " 'model_name': 'FashionMNISTModelV0'}" + ] + }, + "metadata": {}, + "execution_count": 30 + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "DE5sOKMRor_x" - }, "source": [ "Woah, in this case, it looks like adding non-linearities to our model made it perform worse than the baseline.\n", "\n", @@ -2076,13 +3488,13 @@ "Try searching online, \"ways to prevent overfitting in machine learning\" and see what comes up.\n", "\n", "In the meantime, let's take a look at number 1: using a different model." - ] + ], + "metadata": { + "id": "3rOnUnhSpVyX" + } }, { "cell_type": "markdown", - "metadata": { - "id": "6KPj923Ror_x" - }, "source": [ "## TK - 7. Model 2: Building a Convolutional Neural Network (CNN)\n", "\n", @@ -2104,7 +3516,10 @@ "\n", "Where the contents of `[Convolutional layer -> activation layer -> pooling layer]` can be upscaled and repeated multiple times, depending on requirements. \n", "\n" - ] + ], + "metadata": { + "id": "x-45n65jpaYp" + } }, { "cell_type": "markdown", @@ -2133,33 +3548,11 @@ "To do so, we'll leverage the [`nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) and [`nn.MaxPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html) layers from `torch.nn`.\n" ], "metadata": { - "id": "HdaGmkOhVblN" + "id": "VivPp6Gupc6J" } }, { "cell_type": "code", - "execution_count": 1, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/", - "height": 239 - }, - "id": "3GwvKqImor_x", - "outputId": "97b047f3-694f-48df-9c6d-447f44b9bf19" - }, - "outputs": [ - { - "output_type": "error", - "ename": "NameError", - "evalue": "ignored", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Create a convolutional neural network\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mclass\u001b[0m \u001b[0mFashionMNISTModelV2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnn\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mModule\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \"\"\"\n\u001b[1;32m 4\u001b[0m \u001b[0mModel\u001b[0m \u001b[0marchitecture\u001b[0m \u001b[0mcopying\u001b[0m \u001b[0mTinyVGG\u001b[0m \u001b[0;32mfrom\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mhttps\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m//\u001b[0m\u001b[0mpoloclub\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgithub\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mio\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mcnn\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0mexplainer\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mNameError\u001b[0m: name 'nn' is not defined" - ] - } - ], "source": [ "# Create a convolutional neural network \n", "class FashionMNISTModelV2(nn.Module):\n", @@ -2214,6 +3607,45 @@ " hidden_units=10, \n", " output_shape=len(class_names)).to(device)\n", "model_2" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ppiMfmjVpX1h", + "outputId": "e7c8f503-78c7-4e8c-97f4-00dd257b85a4" + }, + "execution_count": 31, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "FashionMNISTModelV2(\n", + " (block_1): Sequential(\n", + " (0): Conv2d(1, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " (1): ReLU()\n", + " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " (3): ReLU()\n", + " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n", + " )\n", + " (block_2): Sequential(\n", + " (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " (1): ReLU()\n", + " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n", + " (3): ReLU()\n", + " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n", + " )\n", + " (classifier): Sequential(\n", + " (0): Flatten(start_dim=1, end_dim=-1)\n", + " (1): Linear(in_features=490, out_features=10, bias=True)\n", + " )\n", + ")" + ] + }, + "metadata": {}, + "execution_count": 31 + } ] }, { @@ -2228,34 +3660,50 @@ "Find a model architecture somewhere and replicate it with code. " ], "metadata": { - "id": "IC_FmcsHbbeh" + "id": "1kGENaszpee9" } }, { "cell_type": "markdown", - "metadata": { - "id": "DS6iwsi_or_x" - }, "source": [ - "### TK - 7.1 Stepping through nn.Conv2d() and nn.MaxPool2d() layers\n", + "### TK - 7.1 Stepping through `nn.Conv2d()` and `nn.MaxPool2d()` layers\n", "\n", "We could start using our model above and see what happens but let's first step through the two new layers we've added:\n", "* [`nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html), also known as a convolutional layer.\n", "* [`nn.MaxPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html), also known as a max pooling layer.\n", "\n", + "> **Question:** What does the \"2d\" in `nn.Conv2d()` stand for?\n", + ">\n", + "> The 2d is for 2-dimensional data. As in, our images have two dimensions: height and width. Yes, there's color channel dimension but each of the color channel dimensions have two dimensions too: height and width.\n", + ">\n", + "> For other dimensional data (such as 1D for text or 3D for 3D objects) there's also `nn.Conv1d()` and `nn.Conv3d()`. \n", + "\n", "To test the layers out, let's create some toy data just like the data used on CNN Explainer." - ] + ], + "metadata": { + "id": "Rm0GTj-Vpi6D" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "torch.manual_seed(42)\n", + "\n", + "# Create sample batch of random numbers with same size as image batch\n", + "images = torch.randn(size=(32, 3, 64, 64)) # [batch_size, color_channels, height, width]\n", + "test_image = images[0] # get a single image for testing\n", + "print(f\"Image batch shape: {images.shape} -> [batch_size, color_channels, height, width]\")\n", + "print(f\"Single image shape: {test_image.shape} -> [color_channels, height, width]\") \n", + "print(f\"Single image pixel values:\\n{test_image}\")" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "3xMO1S0Hor_x", - "outputId": "4d0b8a78-9d28-460e-adb4-8c9ce8094215" + "id": "Ojg2kFSMphQY", + "outputId": "f14dc6be-2cfa-424a-b6dd-0df735ce19db" }, + "execution_count": 32, "outputs": [ { "output_type": "stream", @@ -2289,23 +3737,10 @@ " [-0.4092, 1.5199, 0.2401, ..., -0.2558, 0.7870, 0.9924]]])\n" ] } - ], - "source": [ - "torch.manual_seed(42)\n", - "\n", - "# Create sample batch of random numbers with same size as image batch\n", - "images = torch.randn(size=(32, 3, 64, 64)) # [batch_size, color_channels, height, width]\n", - "test_image = images[0] # get a single image for testing\n", - "print(f\"Image batch shape: {images.shape} -> [batch_size, color_channels, height, width]\")\n", - "print(f\"Single image shape: {test_image.shape} -> [color_channels, height, width]\") \n", - "print(f\"Single image pixel values:\\n{test_image}\")" ] }, { "cell_type": "markdown", - "metadata": { - "id": "d9uW6RYYor_x" - }, "source": [ "Let's create an example `nn.Conv2d()` with various parameters:\n", "* `in_channels` (int) - Number of channels in the input image.\n", @@ -2315,36 +3750,15 @@ "* `padding` (int, tuple, str) - Padding added to all four sides of input. Default: 0.\n", "\n", "![example of going through the different parameters of a Conv2d layer](https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/03-conv2d-layer.gif)\n", + "\n", "*Example of what happens when you change the hyperparameters of a `nn.Conv2d()` layer.*" - ] + ], + "metadata": { + "id": "J_2Ux_i1po2W" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/", - "height": 351 - }, - "id": "CADJvfTKor_x", - "outputId": "545ceb24-f532-48f2-db28-3a505b6dbdc3" - }, - "outputs": [ - { - "output_type": "error", - "ename": "RuntimeError", - "evalue": "ignored", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;31m# Pass the data through the convolutional layer\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mconv_layer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtest_image\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# note: this will error because of shape issues (nn.Conv.2d() expects a 4d tensor as input)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1100\u001b[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks\n\u001b[1;32m 1101\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1102\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1103\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1104\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 444\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 446\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_conv_forward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 447\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 448\u001b[0m \u001b[0;32mclass\u001b[0m \u001b[0mConv3d\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_ConvNd\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py\u001b[0m in \u001b[0;36m_conv_forward\u001b[0;34m(self, input, weight, bias)\u001b[0m\n\u001b[1;32m 441\u001b[0m _pair(0), self.dilation, self.groups)\n\u001b[1;32m 442\u001b[0m return F.conv2d(input, weight, bias, self.stride,\n\u001b[0;32m--> 443\u001b[0;31m self.padding, self.dilation, self.groups)\n\u001b[0m\u001b[1;32m 444\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mRuntimeError\u001b[0m: Expected 4-dimensional input for 4-dimensional weight [10, 3, 3, 3], but got 3-dimensional input of size [3, 64, 64] instead" - ] - } - ], "source": [ "torch.manual_seed(42)\n", "\n", @@ -2358,14 +3772,38 @@ "\n", "# Pass the data through the convolutional layer\n", "conv_layer(test_image) # note: this will error because of shape issues (nn.Conv.2d() expects a 4d tensor as input)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 407 + }, + "id": "eYjuOOi6pnHd", + "outputId": "453a6444-7732-4af9-d2be-43d27ba20385" + }, + "execution_count": 33, + "outputs": [ + { + "output_type": "error", + "ename": "RuntimeError", + "evalue": "ignored", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;31m# Pass the data through the convolutional layer\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mconv_layer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtest_image\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# note: this will error because of shape issues (nn.Conv.2d() expects a 4d tensor as input)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1100\u001b[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks\n\u001b[1;32m 1101\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1102\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1103\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1104\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 444\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 446\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_conv_forward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 447\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 448\u001b[0m \u001b[0;32mclass\u001b[0m \u001b[0mConv3d\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_ConvNd\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py\u001b[0m in \u001b[0;36m_conv_forward\u001b[0;34m(self, input, weight, bias)\u001b[0m\n\u001b[1;32m 441\u001b[0m _pair(0), self.dilation, self.groups)\n\u001b[1;32m 442\u001b[0m return F.conv2d(input, weight, bias, self.stride,\n\u001b[0;32m--> 443\u001b[0;31m self.padding, self.dilation, self.groups)\n\u001b[0m\u001b[1;32m 444\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mRuntimeError\u001b[0m: Expected 4-dimensional input for 4-dimensional weight [10, 3, 3, 3], but got 3-dimensional input of size [3, 64, 64] instead" + ] + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "Qpgx8mj2or_y" - }, "source": [ + "Oh no! Another error.\n", + "\n", "If we try to pass a single image in, we get a shape mismatch error:\n", "\n", "```\n", @@ -2377,18 +3815,25 @@ "Right now our single image `test_image` only has a shape of `[color_channels, height, width]` or `[3, 64, 64]`.\n", "\n", "We can fix this for a single image using `test_image.unsqueeze(dim=0)` to add an extra dimension for `N`." - ] + ], + "metadata": { + "id": "Mu0GFI_3psJH" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Add extra dimension to test image\n", + "test_image.unsqueeze(dim=0).shape" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "l7XrPNuyor_y", - "outputId": "eecf0ab5-6a35-44c4-aa96-602f544fd2e5" + "id": "cRjHf25spwa-", + "outputId": "f4042218-ce4f-4493-b9fc-9e48d44fcc1d" }, + "execution_count": 35, "outputs": [ { "output_type": "execute_result", @@ -2398,24 +3843,24 @@ ] }, "metadata": {}, - "execution_count": 37 + "execution_count": 35 } - ], - "source": [ - "# Add extra dimension to test image\n", - "test_image.unsqueeze(dim=0).shape" ] }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Pass test image with extra dimension through conv_layer\n", + "conv_layer(test_image.unsqueeze(dim=0)).shape" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "_BVfYYLMor_y", - "outputId": "8f7082bb-0b09-4582-e4e0-53371349e958" + "id": "vOe4FE8epydx", + "outputId": "bfaaeac1-0b3e-4093-e9f2-0beb69a21e67" }, + "execution_count": 36, "outputs": [ { "output_type": "execute_result", @@ -2425,47 +3870,23 @@ ] }, "metadata": {}, - "execution_count": 38 + "execution_count": 36 } - ], - "source": [ - "# Pass test image with extra dimension through conv_layer\n", - "conv_layer(test_image.unsqueeze(dim=0)).shape" ] }, { "cell_type": "markdown", - "metadata": { - "id": "vaQZVygvor_y" - }, "source": [ "Hmm, notice what happens to our shape (the same shape as the first layer of TinyVGG on [CNN Explainer](https://poloclub.github.io/cnn-explainer/)), we get different channel sizes as well as different pixel sizes.\n", "\n", "What if we changed the values of `conv_layer`?" - ] + ], + "metadata": { + "id": "gAUUPP4Up1T8" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "-n5R1oWcor_y", - "outputId": "f9e6c742-42d2-4ce5-d7af-f4d1982fb900" - }, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "torch.Size([1, 10, 30, 30])" - ] - }, - "metadata": {}, - "execution_count": 39 - } - ], "source": [ "torch.manual_seed(42)\n", "# Create a new conv_layer with different values (try setting these to whatever you like)\n", @@ -2477,13 +3898,30 @@ "\n", "# Pass single image through new conv_layer_2 (this calls nn.Conv2d()'s forward() method on the input)\n", "conv_layer_2(test_image.unsqueeze(dim=0)).shape" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "CPdcLPpnp4XT", + "outputId": "ec74b9d6-9044-41ec-cb25-1d991bdeab3d" + }, + "execution_count": 37, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "torch.Size([1, 10, 30, 30])" + ] + }, + "metadata": {}, + "execution_count": 37 + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "CmVwgv51or_y" - }, "source": [ "Woah, we get another shape change.\n", "\n", @@ -2502,18 +3940,25 @@ "The only difference is *how* the different layers calculate their parameter updates or in PyTorch terms, the operation present in the layer `forward()` method.\n", "\n", "If we check out our `conv_layer_2.state_dict()` we'll find a similar weight and bias setup as we've seen before." - ] + ], + "metadata": { + "id": "dROW8Kwbp5gz" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Check out the conv_layer_2 internal parameters\n", + "print(conv_layer_2.state_dict())" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "au88sgWEor_y", - "outputId": "9797737f-88c5-4578-8971-c8ad1bdda848" + "id": "3e4TSzmpp7Aa", + "outputId": "258feba1-f19f-47fa-f447-0d69a570db8f" }, + "execution_count": 38, "outputs": [ { "output_type": "stream", @@ -2710,35 +4155,36 @@ " -0.0797, 0.1121]))])\n" ] } - ], - "source": [ - "# Check out the conv_layer_2 internal parameters\n", - "print(conv_layer_2.state_dict())" ] }, { "cell_type": "markdown", - "metadata": { - "id": "ZRyEU-HPor_y" - }, "source": [ "Look at that! A bunch of random numbers for a weight and bias tensor.\n", "\n", "The shapes of these are manipulated by the inputs we passed to `nn.Conv2d()` when we set it up.\n", "\n", "Let's check them out." - ] + ], + "metadata": { + "id": "1s7cGrpwp8OL" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "# Get shapes of weight and bias tensors within conv_layer_2\n", + "print(f\"conv_layer_2 weight shape: \\n{conv_layer_2.weight.shape} -> [out_channels=10, in_channels=3, kernel_size=5, kernel_size=5]\")\n", + "print(f\"\\nconv_layer_2 bias shape: \\n{conv_layer_2.bias.shape} -> [out_channels=10]\")" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "NBT9vb5Lor_y", - "outputId": "6ae0f917-f412-4b41-ae35-5bbe7b9dd755" + "id": "PR8gV7Rop_Cd", + "outputId": "a94962e4-ebb1-4a60-b475-a1957bcc9489" }, + "execution_count": 39, "outputs": [ { "output_type": "stream", @@ -2751,18 +4197,10 @@ "torch.Size([10]) -> [out_channels=10]\n" ] } - ], - "source": [ - "# Get shapes of weight and bias tensors within conv_layer_2\n", - "print(f\"conv_layer_2 weight shape: \\n{conv_layer_2.weight.shape} -> [out_channels=10, in_channels=3, kernel_size=5, kernel_size=5]\")\n", - "print(f\"\\nconv_layer_2 bias shape: \\n{conv_layer_2.bias.shape} -> [out_channels=10]\")" ] }, { "cell_type": "markdown", - "metadata": { - "id": "Rg9xzJynor_y" - }, "source": [ "> **Question:** What should we set the parameters of our `nn.Conv2d()` layers?\n", ">\n", @@ -2777,30 +4215,13 @@ "But the premise remains the same: start with random numbers and update them to better represent the data.\n", "\n", "Now let's check out what happens when we move data through `nn.MaxPool2d()`." - ] + ], + "metadata": { + "id": "5MlfiiXMqAX6" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "iY0mhWjQor_y", - "outputId": "25d667fb-1894-4610-9baa-0921c1de1eff" - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Test image original shape: torch.Size([3, 64, 64])\n", - "Test image with unsqueezed dimension: torch.Size([1, 3, 64, 64])\n", - "Shape after going through conv_layer(): torch.Size([1, 10, 62, 62])\n", - "Shape after going through conv_layer() and max_pool_layer(): torch.Size([1, 10, 31, 31])\n" - ] - } - ], "source": [ "# Print out original image shape without and with unsqueezed dimension\n", "print(f\"Test image original shape: {test_image.shape}\")\n", @@ -2816,13 +4237,30 @@ "# Pass data through the max pool layer\n", "test_image_through_conv_and_max_pool = max_pool_layer(test_image_through_conv)\n", "print(f\"Shape after going through conv_layer() and max_pool_layer(): {test_image_through_conv_and_max_pool.shape}\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "eJfUVP7JqCbA", + "outputId": "009e83ce-8a4e-405b-9872-1f780685041d" + }, + "execution_count": 40, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Test image original shape: torch.Size([3, 64, 64])\n", + "Test image with unsqueezed dimension: torch.Size([1, 3, 64, 64])\n", + "Shape after going through conv_layer(): torch.Size([1, 10, 62, 62])\n", + "Shape after going through conv_layer() and max_pool_layer(): torch.Size([1, 10, 31, 31])\n" + ] + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "vumVHHRVor_y" - }, "source": [ "Notice the change in the shapes of what's happening in and out of a `nn.MaxPool2d()` layer.\n", "\n", @@ -2831,34 +4269,13 @@ "In our case, the shape halves from a `62x62` image to `31x31` image.\n", "\n", "Let's see this work with a smaller tensor." - ] + ], + "metadata": { + "id": "ICAe2oBtqFIO" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "O3fW2FdAor_z", - "outputId": "054836b8-b91b-4e49-c818-57acac8743fd" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Random tensor:\n", - "tensor([[[[0.3367, 0.1288],\n", - " [0.2345, 0.2303]]]])\n", - "Random tensor shape: torch.Size([1, 1, 2, 2])\n", - "\n", - "Max pool tensor:\n", - "tensor([[[[0.3367]]]]) <- this is the maximum value from random_tensor\n", - "Max pool tensor shape: torch.Size([1, 1, 1, 1])\n" - ] - } - ], "source": [ "torch.manual_seed(42)\n", "# Create a random tensor with a similiar number of dimensions to our images\n", @@ -2873,13 +4290,34 @@ "max_pool_tensor = max_pool_layer(random_tensor)\n", "print(f\"\\nMax pool tensor:\\n{max_pool_tensor} <- this is the maximum value from random_tensor\")\n", "print(f\"Max pool tensor shape: {max_pool_tensor.shape}\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "knU2SNx-qD6o", + "outputId": "f0b2132a-ff8d-4991-ad64-fcac0e3d5bc9" + }, + "execution_count": 41, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Random tensor:\n", + "tensor([[[[0.3367, 0.1288],\n", + " [0.2345, 0.2303]]]])\n", + "Random tensor shape: torch.Size([1, 1, 2, 2])\n", + "\n", + "Max pool tensor:\n", + "tensor([[[[0.3367]]]]) <- this is the maximum value from random_tensor\n", + "Max pool tensor shape: torch.Size([1, 1, 1, 1])\n" + ] + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "z0bPUWOOrQGf" - }, "source": [ "Notice the final two dimensions between `random_tensor` and `max_pool_tensor`, they go from `[2, 2]` to `[1, 1]`.\n", "\n", @@ -2914,13 +4352,13 @@ "> **Exercise:** What do you think the [`nn.AvgPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html) layer does? Try making a random tensor like we did above and passing it through. Check the input and output shapes as well as the input and output values.\n", "\n", "> **Extra-curriculum:** Lookup \"most common convolutional neural networks\", what architectures do you find? Are any of them contained within the [`torchvision.models`](https://pytorch.org/vision/stable/models.html) library? What do you think you could do with these?" - ] + ], + "metadata": { + "id": "gz4UbBFLqGdy" + } }, { "cell_type": "markdown", - "metadata": { - "id": "wnklhWU-or_z" - }, "source": [ "### TK - 7.2 Setup a loss function and optimizer\n", "\n", @@ -2937,27 +4375,27 @@ "We'll use the functions as before, `nn.CrossEntropyLoss()` as the loss function (since we're working with multi-class classification data).\n", "\n", "And `torch.optim.SGD()` as the optimizer to optimize `model_2.parameters()` with a learning rate of `0.1`." - ] + ], + "metadata": { + "id": "xdq3qYlCqLo3" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "37JrFK62or_z" - }, - "outputs": [], "source": [ "# Setup loss and optimizer\n", "loss_fn = nn.CrossEntropyLoss()\n", "optimizer = torch.optim.SGD(params=model_2.parameters(), \n", " lr=0.1)" - ] + ], + "metadata": { + "id": "6RiPq-OfqIq0" + }, + "execution_count": 42, + "outputs": [] }, { "cell_type": "markdown", - "metadata": { - "id": "6BM3oe3Vv0v2" - }, "source": [ "### 7.3 Training and testing model_2 using our training and test functions\n", "\n", @@ -2968,42 +4406,13 @@ "We'll use our `train_step()` and `test_step()` functions we created before.\n", "\n", "We'll also measure the time to compare it to our other models." - ] + ], + "metadata": { + "id": "0gogtr-DqOSc" + } }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "3uSvrD71or_z", - "outputId": "f8a98756-66d8-4469-ef17-9f93b7e4554d" - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Epoch: 0\n", - "---------\n", - "Train loss: 0.47664 | Train accuracy: 83.43%\n", - "Test loss: 0.40267 | Test accuracy: 85.72%\n", - "\n", - "Epoch: 1\n", - "---------\n", - "Train loss: 0.47664 | Train accuracy: 83.43%\n", - "Test loss: 0.34160 | Test accuracy: 87.75%\n", - "\n", - "Epoch: 2\n", - "---------\n", - "Train loss: 0.47664 | Train accuracy: 83.43%\n", - "Test loss: 0.32020 | Test accuracy: 88.40%\n", - "\n", - "Train time on cuda: 27.271 seconds\n" - ] - } - ], "source": [ "torch.manual_seed(42)\n", "\n", @@ -3033,43 +4442,53 @@ "total_train_time_model_2 = print_train_time(start=train_time_start_model_2,\n", " end=train_time_end_model_2,\n", " device=device)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "4kicGrI4xAD4" - }, - "source": [ - "Woah! Looks like the convolutional and max pooling layers helped improve performance a little.\n", - "\n", - "Let's evaluate `model_2`'s results with our `eval_model()` function." - ] - }, - { - "cell_type": "code", - "execution_count": null, + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, - "id": "jgcLKasGor_z", - "outputId": "33288e3a-7488-4b2c-bd84-2879a9c6163b" + "id": "raZ9MUupqNDr", + "outputId": "eb43922d-275e-426c-81c2-034e2071d261" }, + "execution_count": 43, "outputs": [ { - "output_type": "execute_result", - "data": { - "text/plain": [ - "{'model_acc': 88.39856230031948,\n", - " 'model_loss': 0.32020142674446106,\n", - " 'model_name': 'FashionMNISTModelV2'}" - ] - }, - "metadata": {}, - "execution_count": 45 + "output_type": "stream", + "name": "stdout", + "text": [ + "Epoch: 0\n", + "---------\n", + "Train loss: 0.47664 | Train accuracy: 83.43%\n", + "Test loss: 0.40529 | Test accuracy: 85.52%\n", + "\n", + "Epoch: 1\n", + "---------\n", + "Train loss: 0.47664 | Train accuracy: 83.43%\n", + "Test loss: 0.35944 | Test accuracy: 86.49%\n", + "\n", + "Epoch: 2\n", + "---------\n", + "Train loss: 0.47664 | Train accuracy: 83.43%\n", + "Test loss: 0.33722 | Test accuracy: 87.54%\n", + "\n", + "Train time on cpu: 195.082 seconds\n" + ] } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Woah! Looks like the convolutional and max pooling layers helped improve performance a little.\n", + "\n", + "Let's evaluate `model_2`'s results with our `eval_model()` function." ], + "metadata": { + "id": "3x0RXD3vqP98" + } + }, + { + "cell_type": "code", "source": [ "# Get model_2 results \n", "model_2_results = eval_model(\n", @@ -3079,13 +4498,32 @@ " accuracy_fn=accuracy_fn\n", ")\n", "model_2_results" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Acv0eUPBqRiO", + "outputId": "cd0157f7-e448-44da-8fc2-42c486915276" + }, + "execution_count": 44, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'model_acc': 87.53993610223642,\n", + " 'model_loss': 0.3372233211994171,\n", + " 'model_name': 'FashionMNISTModelV2'}" + ] + }, + "metadata": {}, + "execution_count": 44 + } ] }, { "cell_type": "markdown", - "metadata": { - "id": "YeQNUElWor_z" - }, "source": [ "## TK - 8. Compare model results and training time\n", "\n", @@ -3100,19 +4538,27 @@ "Building multiple models and performing multiple training experiments to see which performs best.\n", "\n", "Let's combine our model results dictionaries into a DataFrame and find out." - ] + ], + "metadata": { + "id": "GuD2APG7qSfX" + } }, { "cell_type": "code", - "execution_count": null, + "source": [ + "import pandas as pd\n", + "compare_results = pd.DataFrame([model_0_results, model_1_results, model_2_results])\n", + "compare_results" + ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 143 }, - "id": "BEXIA9Ilor_z", - "outputId": "ed8de905-b272-49cb-8cb2-6e7d7d852cc8" + "id": "YVaHEr8bqUcH", + "outputId": "b212f676-f6d0-4a04-e031-c64275dcc707" }, + "execution_count": 45, "outputs": [ { "output_type": "execute_result", @@ -3121,11 +4567,11 @@ " model_name model_loss model_acc\n", "0 FashionMNISTModelV0 0.476639 83.426518\n", "1 FashionMNISTModelV1 0.685001 75.019968\n", - "2 FashionMNISTModelV2 0.320201 88.398562" + "2 FashionMNISTModelV2 0.337223 87.539936" ], "text/html": [ "\n", - "
\n", + "
\n", "
\n", "
\n", "