add annotations to 07

This commit is contained in:
Daniel Bourke committed 2022-06-06 09:01:46 +10:00
1 parent 3cfbdbab9b
commit e0e49a8df4
1 file changed
+85 -128
+85 -128
View File
@@ -760,10 +760,10 @@
"How about we make a helper function to create a custom directory per experiment?\n",
"\n",
"For example, say we'd like to track things like:\n",
"* Experiment date/timestamp - when did the experiment take place?\n",
"* Experiment name - is there something we'd like to call the experiment?\n",
"* Model name - what model was used?\n",
"* Extra - should anything else be tracked?\n",
"* **Experiment date/timestamp** - when did the experiment take place?\n",
"* **Experiment name** - is there something we'd like to call the experiment?\n",
"* **Model name** - what model was used?\n",
"* **Extra** - should anything else be tracked?\n",
"\n",
"You could track almost anything here and be as creative as you want but these should be enough to start.\n",
"\n",
@@ -818,7 +818,7 @@
" else:\n",
" log_dir = os.path.join(\"runs\", timestamp, experiment_name, model_name)\n",
" \n",
" print(f\"[INFO] Created SummaryWriter and saving to {log_dir}...\")\n",
" print(f\"[INFO] Created SummaryWriter instance and saving to: {log_dir}...\")\n",
" return SummaryWriter(log_dir=log_dir)"
]
},
@@ -866,7 +866,7 @@
"\n",
"Our `create_writer()` function works fantastic.\n",
"\n",
"How about we incorporate the ability for our `train()` function to take in a `writer` parameter so we actively update the `SummaryWriter()` instance we're using each time we call `train()`.\n",
"How about we give our `train()` function the ability to take in a `writer` parameter so we actively update the `SummaryWriter()` instance we're using each time we call `train()`.\n",
"\n",
"For example, say we're running a series of experiments, calling `train()` multiple times for multiple different models, it would be good if each experiment used a different `writer`.\n",
"\n",
@@ -881,10 +881,10 @@
"metadata": {},
"outputs": [],
"source": [
"# Add create_writer() to train()\n",
"from typing import Dict, List\n",
"from tqdm.auto import tqdm\n",
"\n",
"# Add writer parameter to train()\n",
"def train(model: torch.nn.Module, \n",
" train_dataloader: torch.utils.data.DataLoader, \n",
" test_dataloader: torch.utils.data.DataLoader, \n",
@@ -892,7 +892,8 @@
" loss_fn: torch.nn.Module,\n",
" epochs: int,\n",
" device: torch.device, \n",
" writer: torch.utils.tensorboard.writer.SummaryWriter) -> Dict[str, List]:\n",
" writer: torch.utils.tensorboard.writer.SummaryWriter # new parameter to take in a writer\n",
" ) -> Dict[str, List]:\n",
" \"\"\"Trains and tests a PyTorch model.\n",
"\n",
" Passes a target PyTorch models through train_step() and test_step()\n",
@@ -1258,8 +1259,8 @@
"\n",
"We're going to create two feature extractor models: \n",
"\n",
"1. `torchvision.models.efficientnet_b0(pretrained=True)` (EffNetB0 for short) backbone + custom classifier head \n",
"2. `torchvision.models.efficientnet_b2(pretrained=True)` (EffNetB2 for short) backbone + custom classifier head\n",
"1. `torchvision.models.efficientnet_b0(pretrained=True)` backbone + custom classifier head (EffNetB0 for short)\n",
"2. `torchvision.models.efficientnet_b2(pretrained=True)` backbone + custom classifier head (EffNetB2 for short)\n",
"\n",
"To do this, we'll freeze the base layers (the feature layers) and update the model's classifier heads (output layers) to suit our problem just like we did in [06. PyTorch Transfer Learning section 3.4](https://www.learnpytorch.io/06_pytorch_transfer_learning/#34-freezing-the-base-model-and-changing-the-output-layer-to-suit-our-needs).\n",
"\n",
@@ -1276,7 +1277,7 @@
"To find the required input shape to the final layer of EffNetB2, let's:\n",
"1. Create an instance of `torchvision.models.efficientnet_b2(pretrained=True)`\n",
"2. See the various input and output shapes by running `torchinfo.summary()`\n",
"3. Print out the number of `in_features` by inspecting `state_dict()` of the classifier portion of EffNetB2 and printing the length of the weight matrix.\n"
"3. Print out the number of `in_features` by inspecting `state_dict()` of the classifier portion of EffNetB2 and printing the length of the weight matrix\n"
]
},
{
@@ -1472,8 +1473,8 @@
"\n",
"| Model | Total parameters (before freezing/changing head) | Total parameters (after freezing/changing head) | Total trainable parameters (after freezing/changing head) |\n",
"| ----- | ----- | ----- | ----- |\n",
"| `torchvision.models.efficientnet_b0(pretrained=True)` | 5,288,548 | 4,011,391 | 3,843 | \n",
"| `torchvision.models.efficientnet_b2(pretrained=True)` | 9,109,994 | 7,705,221 | 4,227 |\n",
"| EfficientNetB0 | 5,288,548 | 4,011,391 | 3,843 | \n",
"| EfficientNetB2 | 9,109,994 | 7,705,221 | 4,227 |\n",
"\n",
"This gives the backbone of the EffNetB2 model more opportunities to form a representation of our pizza, steak and sushi data.\n",
"\n",
@@ -1527,12 +1528,28 @@
"\n",
"Now we can write code to iterate through each of the different options and try out each of the different combinations.\n",
"\n",
"UPTOHERE... writing code to iterate through experiments, track the results and save the trained model at the end of each experiment"
"We'll also save the model at the end of each experiment so later on we can load back in the best model and use it for making predictions.\n",
"\n",
"Specifically, let's go through the following steps: \n",
"1. Set the random seeds (so our experiment results are reproducible, in practice, you might run the same experiment across ~3 different seeds and average the results).\n",
"2. Keep track of different experiment numbers (this is mostly for pretty print outs).\n",
"3. Loop through the `train_dataloaders` dictionary items for each of the different training DataLoaders.\n",
"4. Loop through the list of epoch numbers.\n",
"5. Loop through the list of different model names.\n",
"6. Check which model is the target model and create a new EffNetB0 or EffNetB2 instance (we create a new model instance each experiment so all models start from the same standpoint).\n",
"7. Create information print outs for the current running experiment (so we know what's happening).\n",
"8. Create a new loss function (`torch.nn.CrossEntropyLoss()`) and optimizer (`torch.optim.Adam(params=model.parameters(), lr=0.001)`) for each new experiment.\n",
"9. Train the model with the modified `train()` function passing the appropriate details to the `writer` parameter.\n",
"10. Save the trained model with an appropriate file name to file with `save_model()` from [`utils.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/utils.py). \n",
"\n",
"We can also use the `%%time` magic to see how long all of our experiments take together in a single Jupyter/Google Colab cell.\n",
"\n",
"Let's do it!"
]
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": 45,
"metadata": {},
"outputs": [
{
@@ -1540,17 +1557,17 @@
"output_type": "stream",
"text": [
"[INFO] Creating new effnetb0 model.\n",
"[INFO] Experiment number: 1\n",
"[INFO] Model: effnetb0\n",
"[INFO] DataLoader: data_10_percent\n",
"[INFO] Training for 5 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_10_percent/effnetb0/5_epochs...\n"
"[INFO] Created SummaryWriter and saving to runs/2022-06-06/data_10_percent/effnetb0/5_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "cc8964778c7544b4852f8ff033ef6d56",
"model_id": "5839073db6fa45f39a30f5d4e673e273",
"version_major": 2,
"version_minor": 0
},
@@ -1571,20 +1588,20 @@
"Epoch: 4 | train_loss: 0.7096 | train_acc: 0.7578 | test_loss: 0.5920 | test_acc: 0.8864\n",
"Epoch: 5 | train_loss: 0.5999 | train_acc: 0.9062 | test_loss: 0.5689 | test_acc: 0.8864\n",
"[INFO] Saving model to: models/07_effnetb0_data_10_percent_5_epochs.pth\n",
"----------\n",
"------------------------------\n",
"\n",
"[INFO] Creating new effnetb2 model.\n",
"[INFO] Experiment number: 1\n",
"[INFO] Model: effnetb2\n",
"[INFO] DataLoader: data_10_percent\n",
"[INFO] Training for 5 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_10_percent/effnetb2/5_epochs...\n"
"[INFO] Created SummaryWriter and saving to runs/2022-06-06/data_10_percent/effnetb2/5_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "5178dfd761384633b24dc26d936e1ec6",
"model_id": "2ebd1bd98f8844f69b302ef5dfca652c",
"version_major": 2,
"version_minor": 0
},
@@ -1605,20 +1622,20 @@
"Epoch: 4 | train_loss: 0.7182 | train_acc: 0.8867 | test_loss: 0.7161 | test_acc: 0.9081\n",
"Epoch: 5 | train_loss: 0.6847 | train_acc: 0.7656 | test_loss: 0.7087 | test_acc: 0.8873\n",
"[INFO] Saving model to: models/07_effnetb2_data_10_percent_5_epochs.pth\n",
"----------\n",
"------------------------------\n",
"\n",
"[INFO] Creating new effnetb0 model.\n",
"[INFO] Experiment number: 1\n",
"[INFO] Model: effnetb0\n",
"[INFO] DataLoader: data_10_percent\n",
"[INFO] Training for 10 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_10_percent/effnetb0/10_epochs...\n"
"[INFO] Created SummaryWriter and saving to runs/2022-06-06/data_10_percent/effnetb0/10_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "5e6e13dc6eb8489d8abfee348dea8bab",
"model_id": "454629e5fd9046cb811e86a58f82f25e",
"version_major": 2,
"version_minor": 0
},
@@ -1644,20 +1661,20 @@
"Epoch: 9 | train_loss: 0.5729 | train_acc: 0.7695 | test_loss: 0.5120 | test_acc: 0.8873\n",
"Epoch: 10 | train_loss: 0.4782 | train_acc: 0.8242 | test_loss: 0.4650 | test_acc: 0.9072\n",
"[INFO] Saving model to: models/07_effnetb0_data_10_percent_10_epochs.pth\n",
"----------\n",
"------------------------------\n",
"\n",
"[INFO] Creating new effnetb2 model.\n",
"[INFO] Experiment number: 1\n",
"[INFO] Model: effnetb2\n",
"[INFO] DataLoader: data_10_percent\n",
"[INFO] Training for 10 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_10_percent/effnetb2/10_epochs...\n"
"[INFO] Created SummaryWriter and saving to runs/2022-06-06/data_10_percent/effnetb2/10_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ad2081cc018e4febac72e788a1b1d2f2",
"model_id": "2fb31c5f17c243e79ca379ca8b585cb2",
"version_major": 2,
"version_minor": 0
},
@@ -1683,20 +1700,20 @@
"Epoch: 9 | train_loss: 0.5421 | train_acc: 0.8086 | test_loss: 0.6231 | test_acc: 0.8769\n",
"Epoch: 10 | train_loss: 0.4919 | train_acc: 0.8086 | test_loss: 0.5879 | test_acc: 0.8873\n",
"[INFO] Saving model to: models/07_effnetb2_data_10_percent_10_epochs.pth\n",
"----------\n",
"------------------------------\n",
"\n",
"[INFO] Creating new effnetb0 model.\n",
"[INFO] Experiment number: 1\n",
"[INFO] Model: effnetb0\n",
"[INFO] DataLoader: data_20_percent\n",
"[INFO] Training for 5 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_20_percent/effnetb0/5_epochs...\n"
"[INFO] Created SummaryWriter and saving to runs/2022-06-06/data_20_percent/effnetb0/5_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "cb4a70bb37eb4489a926d26bc3699f70",
"model_id": "50171f6a32ef4133a0f3b7539563815a",
"version_major": 2,
"version_minor": 0
},
@@ -1717,20 +1734,20 @@
"Epoch: 4 | train_loss: 0.4937 | train_acc: 0.8646 | test_loss: 0.4454 | test_acc: 0.9176\n",
"Epoch: 5 | train_loss: 0.4886 | train_acc: 0.8500 | test_loss: 0.3913 | test_acc: 0.9176\n",
"[INFO] Saving model to: models/07_effnetb0_data_20_percent_5_epochs.pth\n",
"----------\n",
"------------------------------\n",
"\n",
"[INFO] Creating new effnetb2 model.\n",
"[INFO] Experiment number: 1\n",
"[INFO] Model: effnetb2\n",
"[INFO] DataLoader: data_20_percent\n",
"[INFO] Training for 5 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_20_percent/effnetb2/5_epochs...\n"
"[INFO] Created SummaryWriter and saving to runs/2022-06-06/data_20_percent/effnetb2/5_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8af63629be6e4d238e9b351041904715",
"model_id": "62ae96db47d147be9aa6a485c9655c48",
"version_major": 2,
"version_minor": 0
},
@@ -1751,20 +1768,20 @@
"Epoch: 4 | train_loss: 0.5429 | train_acc: 0.8354 | test_loss: 0.5685 | test_acc: 0.8977\n",
"Epoch: 5 | train_loss: 0.4410 | train_acc: 0.8708 | test_loss: 0.4470 | test_acc: 0.9384\n",
"[INFO] Saving model to: models/07_effnetb2_data_20_percent_5_epochs.pth\n",
"----------\n",
"------------------------------\n",
"\n",
"[INFO] Creating new effnetb0 model.\n",
"[INFO] Experiment number: 1\n",
"[INFO] Model: effnetb0\n",
"[INFO] DataLoader: data_20_percent\n",
"[INFO] Training for 10 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_20_percent/effnetb0/10_epochs...\n"
"[INFO] Created SummaryWriter and saving to runs/2022-06-06/data_20_percent/effnetb0/10_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c6c0e83ad89140fd83a99d9d574985bf",
"model_id": "0fa614cf200a4ea0af509c098bb2de66",
"version_major": 2,
"version_minor": 0
},
@@ -1787,69 +1804,7 @@
"Epoch: 6 | train_loss: 0.3708 | train_acc: 0.8833 | test_loss: 0.3565 | test_acc: 0.9072\n",
"Epoch: 7 | train_loss: 0.3558 | train_acc: 0.9208 | test_loss: 0.3182 | test_acc: 0.9072\n",
"Epoch: 8 | train_loss: 0.3739 | train_acc: 0.8938 | test_loss: 0.3346 | test_acc: 0.8977\n",
"Epoch: 9 | train_loss: 0.2975 | train_acc: 0.9375 | test_loss: 0.3088 | test_acc: 0.9280\n",
"Epoch: 10 | train_loss: 0.3625 | train_acc: 0.8479 | test_loss: 0.2771 | test_acc: 0.9072\n",
"[INFO] Saving model to: models/07_effnetb0_data_20_percent_10_epochs.pth\n",
"----------\n",
"\n",
"[INFO] Creating new effnetb2 model.\n",
"[INFO] Model: effnetb2\n",
"[INFO] DataLoader: data_20_percent\n",
"[INFO] Training for 10 epochs\n",
"----------\n",
"[INFO] Created SummaryWriter and saving to runs/2022-06-04/data_20_percent/effnetb2/10_epochs...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "2cac013b0b02400f87dcab3da67fae9f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/10 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 1 | train_loss: 0.9819 | train_acc: 0.5604 | test_loss: 0.7775 | test_acc: 0.8049\n",
"Epoch: 2 | train_loss: 0.7298 | train_acc: 0.8021 | test_loss: 0.6665 | test_acc: 0.8873\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Exception ignored in: <function _releaseLock at 0x7f9827c91ca0>\n",
"Traceback (most recent call last):\n",
" File \"/home/daniel/code/pytorch/env/lib/python3.9/logging/__init__.py\", line 227, in _releaseLock\n",
" def _releaseLock():\n",
"KeyboardInterrupt: \n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 3 | train_loss: 0.6011 | train_acc: 0.8458 | test_loss: 0.5633 | test_acc: 0.9280\n",
"Epoch: 4 | train_loss: 0.5429 | train_acc: 0.8354 | test_loss: 0.5685 | test_acc: 0.8977\n",
"Epoch: 5 | train_loss: 0.4410 | train_acc: 0.8708 | test_loss: 0.4470 | test_acc: 0.9384\n",
"Epoch: 6 | train_loss: 0.3876 | train_acc: 0.9125 | test_loss: 0.4564 | test_acc: 0.8977\n",
"Epoch: 7 | train_loss: 0.3481 | train_acc: 0.9271 | test_loss: 0.4227 | test_acc: 0.9384\n",
"Epoch: 8 | train_loss: 0.3861 | train_acc: 0.8792 | test_loss: 0.4350 | test_acc: 0.9280\n",
"Epoch: 9 | train_loss: 0.3315 | train_acc: 0.8979 | test_loss: 0.4254 | test_acc: 0.9081\n",
"Epoch: 10 | train_loss: 0.3382 | train_acc: 0.8979 | test_loss: 0.3909 | test_acc: 0.9384\n",
"[INFO] Saving model to: models/07_effnetb2_data_20_percent_10_epochs.pth\n",
"----------\n",
"\n",
"CPU times: user 37.2 s, sys: 48.4 s, total: 1min 25s\n",
"Wall time: 1min 40s\n"
"Epoch: 9 | train_loss: 0.2975 | train_acc: 0.9375 | test_loss: 0.3088 | test_acc: 0.9280\n"
]
}
],
@@ -1857,53 +1812,55 @@
"%%time\n",
"from going_modular.going_modular.utils import save_model\n",
"\n",
"# Set the random seeds\n",
"set_seeds()\n",
"# 1. Set the random seeds\n",
"set_seeds(seed=42)\n",
"\n",
"# Loop through each DataLoader\n",
"# 2. Keep track of experiment numbers\n",
"experiment_number = 0\n",
"\n",
"# 3. Loop through each DataLoader\n",
"for dataloader_name, train_dataloader in train_dataloaders.items():\n",
"\n",
" # Loop through each number of epochs\n",
" # 4. Loop through each number of epochs\n",
" for epochs in num_epochs: \n",
"\n",
" # Loop through each model name and create a new model based on the name\n",
" # 5. Loop through each model name and create a new model based on the name\n",
" for model_name in models:\n",
"\n",
" # Select the model\n",
" # 6. Select the model\n",
" if model_name == \"effnetb0\":\n",
" model = create_effnetb0() # creates a new model each time (important because we want each experiment to start from scratch)\n",
" else:\n",
" model = create_effnetb2() # creates a new model each time (important because we want each experiment to start from scratch)\n",
" \n",
" # Create information print outs\n",
" # 7. Create information print outs\n",
" print(f\"[INFO] Experiment number: {experiment_number+1}\")\n",
" print(f\"[INFO] Model: {model_name}\")\n",
" print(f\"[INFO] DataLoader: {dataloader_name}\")\n",
" print(f\"[INFO] Training for {epochs} epochs\")\n",
" print(f\"----------\") \n",
" print(f\"[INFO] Number of epochs: {epochs}\") \n",
" \n",
" # Create a new loss and optimizer for every model\n",
" # 8. Create a new loss and optimizer for every model\n",
" loss_fn = nn.CrossEntropyLoss()\n",
" optimizer = torch.optim.Adam(params=model.parameters(), lr=0.001)\n",
"\n",
" # Train target model with target dataloaders and track experiments\n",
" # 9. Train target model with target dataloaders and track experiments\n",
" train(model=model,\n",
" train_dataloader=train_dataloader,\n",
" test_dataloader=test_dataloader, \n",
" optimizer=optimizer,\n",
" loss_fn=loss_fn,\n",
" epochs=epochs,\n",
" device=device,\n",
" writer=create_writer(experiment_name=dataloader_name,\n",
" model_name=model_name,\n",
" extra=f\"{epochs}_epochs\"\n",
" ))\n",
" train_dataloader=train_dataloader,\n",
" test_dataloader=test_dataloader, \n",
" optimizer=optimizer,\n",
" loss_fn=loss_fn,\n",
" epochs=epochs,\n",
" device=device,\n",
" writer=create_writer(experiment_name=dataloader_name,\n",
" model_name=model_name,\n",
" extra=f\"{epochs}_epochs\"))\n",
" \n",
" # Save the model to file so we can get back the best model\n",
" # 10. Save the model to file so we can get back the best model\n",
" save_filepath = f\"07_{model_name}_{dataloader_name}_{epochs}_epochs.pth\"\n",
" save_model(model=model,\n",
" target_dir=\"models\",\n",
" model_name=save_filepath)\n",
" print(\"----------\\n\")"
" print(\"-\"*30 + \"\\n\")"
]
},
{