Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 135 additions & 12 deletions notebooks/unit4/lesson_31/Lesson_31_activity.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -232,17 +232,6 @@
" nn.MaxPool2d(2, 2),\n",
" nn.Dropout(0.5),\n",
" \n",
" # TODO: Add more convolutional blocks here\n",
" # Example (uncomment and modify):\n",
" # nn.Conv2d(32, 64, kernel_size=3, padding=1),\n",
" # nn.BatchNorm2d(64),\n",
" # nn.ReLU(),\n",
" # nn.Conv2d(64, 64, kernel_size=3, padding=1),\n",
" # nn.BatchNorm2d(64),\n",
" # nn.ReLU(),\n",
" # nn.MaxPool2d(2, 2),\n",
" # nn.Dropout(0.5),\n",
" \n",
" # Classifier\n",
" nn.Flatten(),\n",
" nn.Linear(32 * 16 * 16, 128), # TODO: Update input size if you add more layers\n",
Expand All @@ -264,6 +253,101 @@
"### 1.4. Train Modified Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8e4102e5",
"metadata": {},
"outputs": [],
"source": [
"def train_model(\n",
" model: nn.Module,\n",
" train_loader: DataLoader,\n",
" val_loader: DataLoader,\n",
" criterion: nn.Module,\n",
" optimizer: optim.Optimizer,\n",
" epochs: int = 10,\n",
" print_every: int = 1\n",
") -> dict[str, list[float]]:\n",
" '''Training loop for PyTorch classification model.\n",
" \n",
" Note: Assumes data is already on the correct device.\n",
" '''\n",
"\n",
" history = {'train_loss': [], 'val_loss': [], 'train_accuracy': [], 'val_accuracy': []}\n",
"\n",
" for epoch in range(epochs):\n",
"\n",
" # Training phase\n",
" model.train()\n",
" running_loss = 0.0\n",
" correct = 0\n",
" total = 0\n",
"\n",
" for images, labels in train_loader:\n",
"\n",
" # Forward pass\n",
" optimizer.zero_grad()\n",
" outputs = model(images)\n",
" loss = criterion(outputs, labels)\n",
"\n",
" # Backward pass\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
" # Track metrics\n",
" running_loss += loss.item()\n",
" _, predicted = torch.max(outputs.data, 1)\n",
" total += labels.size(0)\n",
" correct += (predicted == labels).sum().item()\n",
"\n",
" # Calculate training metrics\n",
" train_loss = running_loss / len(train_loader)\n",
" train_accuracy = 100 * correct / total\n",
"\n",
" # Validation phase\n",
" model.eval()\n",
" val_running_loss = 0.0\n",
" val_correct = 0\n",
" val_total = 0\n",
"\n",
" with torch.no_grad():\n",
"\n",
" for images, labels in val_loader:\n",
"\n",
" outputs = model(images)\n",
" loss = criterion(outputs, labels)\n",
"\n",
" val_running_loss += loss.item()\n",
" _, predicted = torch.max(outputs.data, 1)\n",
" val_total += labels.size(0)\n",
" val_correct += (predicted == labels).sum().item()\n",
"\n",
" val_loss = val_running_loss / len(val_loader)\n",
" val_accuracy = 100 * val_correct / val_total\n",
"\n",
" # Record metrics\n",
" history['train_loss'].append(train_loss)\n",
" history['val_loss'].append(val_loss)\n",
" history['train_accuracy'].append(train_accuracy)\n",
" history['val_accuracy'].append(val_accuracy)\n",
"\n",
" # Print progress\n",
" if (epoch + 1) % print_every == 0 or epoch == 0:\n",
"\n",
" print(\n",
" f'Epoch {epoch+1}/{epochs} - ' +\n",
" f'loss: {train_loss:.4f} - ' +\n",
" f'accuracy: {train_accuracy:.2f}% - ' +\n",
" f'val_loss: {val_loss:.4f} - ' +\n",
" f'val_accuracy: {val_accuracy:.2f}%'\n",
" )\n",
"\n",
" print('\\nTraining complete.')\n",
"\n",
" return history"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand Down Expand Up @@ -295,6 +379,45 @@
"### 1.5. Evaluate and Visualize Results"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "08942db9",
"metadata": {},
"outputs": [],
"source": [
"def evaluate_model(\n",
" model: nn.Module,\n",
" test_loader: DataLoader\n",
") -> tuple[float, np.ndarray, np.ndarray]:\n",
" '''Evaluate model on test set.\n",
" \n",
" Note: Assumes data is already on the correct device.\n",
" '''\n",
"\n",
" model.eval()\n",
" correct = 0\n",
" total = 0\n",
" all_predictions = []\n",
" all_labels = []\n",
"\n",
" with torch.no_grad():\n",
"\n",
" for images, labels in test_loader:\n",
"\n",
" outputs = model(images)\n",
" _, predicted = torch.max(outputs.data, 1)\n",
"\n",
" total += labels.size(0)\n",
" correct += (predicted == labels).sum().item()\n",
"\n",
" all_predictions.extend(predicted.cpu().numpy())\n",
" all_labels.extend(labels.cpu().numpy())\n",
"\n",
" accuracy = 100 * correct / total\n",
" return accuracy, np.array(all_predictions), np.array(all_labels)"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand Down Expand Up @@ -495,7 +618,7 @@
"# TODO: Update the first conv layer to accept 3 channels\n",
"model_exp2 = nn.Sequential(\n",
" # Conv block: TODO: Change input channels from 1 to 3\n",
" nn.Conv2d(1, 32, kernel_size=3, padding=1), # TODO: Change first argument to 3\n",
" nn.Conv2d(1, 32, kernel_size=3, padding=1),\n",
" nn.BatchNorm2d(32),\n",
" nn.ReLU(),\n",
" nn.Conv2d(32, 32, kernel_size=3, padding=1),\n",
Expand Down
159 changes: 159 additions & 0 deletions notebooks/unit4/lesson_31/Lesson_31_demo.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,101 @@
"### 2.3. Train model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b5f22f21",
"metadata": {},
"outputs": [],
"source": [
"def train_model(\n",
" model: nn.Module,\n",
" train_loader: DataLoader,\n",
" val_loader: DataLoader,\n",
" criterion: nn.Module,\n",
" optimizer: optim.Optimizer,\n",
" epochs: int = 10,\n",
" print_every: int = 1\n",
") -> dict[str, list[float]]:\n",
" '''Training loop for PyTorch classification model.\n",
" \n",
" Note: Assumes data is already on the correct device.\n",
" '''\n",
"\n",
" history = {'train_loss': [], 'val_loss': [], 'train_accuracy': [], 'val_accuracy': []}\n",
"\n",
" for epoch in range(epochs):\n",
"\n",
" # Training phase\n",
" model.train()\n",
" running_loss = 0.0\n",
" correct = 0\n",
" total = 0\n",
"\n",
" for images, labels in train_loader:\n",
"\n",
" # Forward pass\n",
" optimizer.zero_grad()\n",
" outputs = model(images)\n",
" loss = criterion(outputs, labels)\n",
"\n",
" # Backward pass\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
" # Track metrics\n",
" running_loss += loss.item()\n",
" _, predicted = torch.max(outputs.data, 1)\n",
" total += labels.size(0)\n",
" correct += (predicted == labels).sum().item()\n",
"\n",
" # Calculate training metrics\n",
" train_loss = running_loss / len(train_loader)\n",
" train_accuracy = 100 * correct / total\n",
"\n",
" # Validation phase\n",
" model.eval()\n",
" val_running_loss = 0.0\n",
" val_correct = 0\n",
" val_total = 0\n",
"\n",
" with torch.no_grad():\n",
"\n",
" for images, labels in val_loader:\n",
"\n",
" outputs = model(images)\n",
" loss = criterion(outputs, labels)\n",
"\n",
" val_running_loss += loss.item()\n",
" _, predicted = torch.max(outputs.data, 1)\n",
" val_total += labels.size(0)\n",
" val_correct += (predicted == labels).sum().item()\n",
"\n",
" val_loss = val_running_loss / len(val_loader)\n",
" val_accuracy = 100 * val_correct / val_total\n",
"\n",
" # Record metrics\n",
" history['train_loss'].append(train_loss)\n",
" history['val_loss'].append(val_loss)\n",
" history['train_accuracy'].append(train_accuracy)\n",
" history['val_accuracy'].append(val_accuracy)\n",
"\n",
" # Print progress\n",
" if (epoch + 1) % print_every == 0 or epoch == 0:\n",
"\n",
" print(\n",
" f'Epoch {epoch+1}/{epochs} - ' +\n",
" f'loss: {train_loss:.4f} - ' +\n",
" f'accuracy: {train_accuracy:.2f}% - ' +\n",
" f'val_loss: {val_loss:.4f} - ' +\n",
" f'val_accuracy: {val_accuracy:.2f}%'\n",
" )\n",
"\n",
" print('\\nTraining complete.')\n",
"\n",
" return history"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand Down Expand Up @@ -387,6 +482,45 @@
"### 3.1. Calculate test accuracy"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "59bdd8c6",
"metadata": {},
"outputs": [],
"source": [
"def evaluate_model(\n",
" model: nn.Module,\n",
" test_loader: DataLoader\n",
") -> tuple[float, np.ndarray, np.ndarray]:\n",
" '''Evaluate model on test set.\n",
" \n",
" Note: Assumes data is already on the correct device.\n",
" '''\n",
"\n",
" model.eval()\n",
" correct = 0\n",
" total = 0\n",
" all_predictions = []\n",
" all_labels = []\n",
"\n",
" with torch.no_grad():\n",
"\n",
" for images, labels in test_loader:\n",
"\n",
" outputs = model(images)\n",
" _, predicted = torch.max(outputs.data, 1)\n",
"\n",
" total += labels.size(0)\n",
" correct += (predicted == labels).sum().item()\n",
"\n",
" all_predictions.extend(predicted.cpu().numpy())\n",
" all_labels.extend(labels.cpu().numpy())\n",
"\n",
" accuracy = 100 * correct / total\n",
" return accuracy, np.array(all_predictions), np.array(all_labels)"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand Down Expand Up @@ -581,6 +715,31 @@
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "e7652023",
"metadata": {},
"source": [
"## 4. Save model for inference"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6743f566",
"metadata": {},
"outputs": [],
"source": [
"# Define model save path\n",
"model_dir = Path('../models')\n",
"model_dir.mkdir(parents=True, exist_ok=True)\n",
"model_path = model_dir / 'cifar10_cnn_model.pth'\n",
"\n",
"# Save the model state dict (recommended for inference)\n",
"torch.save(model.state_dict(), model_path)\n",
"print(f'Model saved to: {model_path.resolve()}')"
]
}
],
"metadata": {
Expand Down