Skip to content

Commit 249e148

Browse files
Create 05_training_process_.md
1 parent 9808905 commit 249e148

File tree

1 file changed

+153
-0
lines changed

1 file changed

+153
-0
lines changed

05_training_process_.md

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
# Chapter 5: Training Process
2+
3+
Welcome back! In our previous chapters, we've set the stage for training our custom object detection model. We configured our workspace in [Chapter 1: Google Colab Environment](01_google_colab_environment_.md), told Darknet about our data and what objects to find in [Chapter 2: Dataset Configuration (.data, .names, train.txt)](02_dataset_configuration___data___names__train_txt__.md), configured the model's blueprint in [Chapter 3: YOLOv3 Model Configuration (.cfg)](03_yolov3_model_configuration___cfg__.md), and prepared the Darknet framework engine itself in [Chapter 4: Darknet Framework](04_darknet_framework_.md).
4+
5+
Now, it's time for the main event: **Training!**
6+
7+
### The Problem: Making the Model Learn
8+
9+
Imagine you have a puppy that needs to learn to fetch specific toys ("job" blocks and "beam_number" sticks, perhaps). Initially, the puppy doesn't know the difference. You have to show it examples: "This is a 'job' block," or "Go get the 'beam_number' stick!" When it brings back the wrong thing, you correct it. Over time, with many examples and corrections, the puppy learns to identify and fetch the right object.
10+
11+
Our YOLOv3 model is similar to that puppy. It starts with random internal numbers (weights) and doesn't know what a "job" or "beam_number" looks like. The **training process** is how we teach the model, using our dataset of images and their corresponding labels, to identify the objects we defined.
12+
13+
This is the phase where the model analyzes the training images, attempts to make predictions, compares those predictions to the correct labels (ground truth), calculates how wrong it was, and then adjusts its internal parameters (weights) to get a little bit better. This cycle repeats thousands of times until the model becomes proficient at locating and classifying our target objects.
14+
15+
### The Core Command: Starting the Engine
16+
17+
Everything we prepared in the previous steps culminates in a single command that tells the Darknet framework to start this iterative learning process. This command brings together the dataset configuration, the model configuration, and initial learned patterns from a pre-trained model.
18+
19+
Here is the command we run in Colab:
20+
21+
```bash
22+
!./darknet detector train data/obj.data cfg/yolov3_training.cfg darknet53.conv.74 -dont_show
23+
```
24+
25+
Let's break down each part of this crucial command, remembering what we learned in the previous chapters:
26+
27+
* `!`: Tells Colab to execute this as a shell command.
28+
* `./darknet`: This is the executable Darknet program we compiled in [Chapter 4](04_darknet_framework_.md). The `./` means "look for it in the current directory" (which should be the `darknet` directory because we used `%cd darknet`).
29+
* `detector train`: These are subcommands telling the `darknet` program *what* to do. `detector` means we're working with object detection models, and `train` means we want to start the training procedure.
30+
* `data/obj.data`: This is the path to our dataset configuration file ([Chapter 2](02_dataset_configuration___data___names__train_txt__.md)). Darknet reads this first to know the number of classes, where the image lists (`train.txt`, `test.txt`) and names file (`obj.names`) are, and where to save the trained model weights.
31+
* `cfg/yolov3_training.cfg`: This is the path to our modified YOLOv3 model configuration file ([Chapter 3](03_yolov3_model_configuration___cfg__.md)). Darknet reads this to build the neural network structure itself, defining layers, sizes, batch parameters, learning rates, and the total number of training iterations (`max_batches`).
32+
* `darknet53.conv.74`: This is the path to the file containing pre-trained weights for a large portion of the YOLOv3 network. These weights come from training on a massive dataset (like ImageNet). Using these as a starting point, instead of random weights, helps our model learn much faster and often achieve better results, especially with smaller custom datasets. This technique is called **transfer learning**.
33+
* `-dont_show`: This is an optional flag. In some environments, Darknet might try to pop up a window to visualize the training process or detections. Since Colab is a cloud environment without a display, this flag prevents those windows from appearing, which would otherwise cause an error.
34+
35+
When you run this code cell, Darknet will start the training process.
36+
37+
### What You'll See During Training
38+
39+
Once the command starts, the Colab cell will begin outputting information printed by the Darknet framework. This output shows the progress of the training process. It will look like a stream of text, updating periodically.
40+
41+
Here's a simplified look at what some of the output lines mean:
42+
43+
```
44+
Loading weights from darknet53.conv.74... Done!
45+
Learning Rate: 0.001
46+
Batch # 1, 1.973020 avg, 0.134516 rate , 2.643892 seconds , 64 images
47+
Batch # 2, 1.859411 avg, 0.141291 rate , 2.540123 seconds , 128 images
48+
Batch # 3, 1.745801 avg, 0.131418 rate , 2.687651 seconds , 192 images
49+
...
50+
Region Avg IOU: 0.781737, Class: 0.998916, Obj: 0.999353, No Obj: 0.000216, Avg Recall: 0.987805, Avg Precision: 0.990000, Avg F1: 0.988902, Loss: 1.245678, Vloss: 0.123456, .5R: 1.000000, .7R: 0.975610, count: 82
51+
Batch # 100, 1.156789 avg, 0.128975 rate , 2.756789 seconds , 6400 images
52+
... (many more lines)
53+
```
54+
55+
Key things to look for:
56+
57+
1. **`Batch #`**: This indicates the current training iteration or step. Darknet will train for `max_batches` total iterations (which we set to 4000 in [Chapter 3](03_yolov3_model_configuration___cfg__.md)).
58+
2. **`avg`**: This is the **average loss**. The 'loss' is a number that tells us how "wrong" the model's predictions were in the current batch of images. A lower loss means better predictions. The `avg` loss is a smoothed average over previous batches. **This number should generally decrease over time** as the model learns. Watching the `avg` loss go down is how you know your training is progressing well.
59+
3. **`rate`**: The learning rate, which controls how big of a step the model takes when adjusting its weights based on the loss.
60+
4. **`seconds`**: Time taken for the current batch.
61+
5. **`images`**: Total number of images processed so far.
62+
6. **`Loss`**: The loss calculated for the current batch.
63+
7. Other metrics like `Avg IOU`, `Class`, `Obj`, `Avg Recall`, `Avg Precision` provide more detailed insights into performance, but for beginners, focusing on the `avg` loss decreasing is the most important indicator of successful training.
64+
65+
Darknet will print this information periodically (e.g., every 10 or 100 batches).
66+
67+
### Saving Progress: Weights Files
68+
69+
Training can take a significant amount of time (minutes to hours depending on dataset size and `max_batches`). It's important to save the model's learned weights regularly so you don't lose progress if your Colab session disconnects or the training stops.
70+
71+
Darknet does this automatically! Based on the `backup = /content/weight` line in our `data/obj.data` file ([Chapter 2](02_dataset_configuration___data___names__train_txt__.md)), Darknet will save weight files periodically in a directory it creates named `weight` inside the `/content/` directory (which is inside the temporary Colab VM).
72+
73+
It typically saves:
74+
* Weights every 100 iterations for the first 1000 iterations (e.g., `yolov3_training_100.weights`, `yolov3_training_200.weights`, ...).
75+
* Weights every 1000 iterations after that.
76+
* A file named `yolov3_training_last.weights` very frequently. This file contains the weights from the *most recent* training batch.
77+
78+
**Important:** As noted in [Chapter 2](02_dataset_configuration___data___names__train_txt__.md), the path `/content/weight` is temporary. To save your weights permanently, you would typically change the `backup` path in `data/obj.data` to point to a location in your mounted Google Drive, like `/content/gdrive/MyDrive/Yolo_v3/backup_weights`. You would also need to create this directory in Google Drive before starting training.
79+
80+
### Stopping and Resuming Training
81+
82+
* **Stopping:** You can stop the training process manually by clicking the square "Stop" button in the top left of the Colab cell that is running the training command, or by pressing `Ctrl + C` if you were running from a terminal. Darknet will usually print a message indicating it is saving the final weights before exiting.
83+
* **Resuming:** If your training stopped before reaching `max_batches`, you can resume it from the last saved weights. The project snippet includes a commented-out line for this:
84+
85+
```bash
86+
# Uncomment below and comment above to re-start your training from last saved weights
87+
#!./darknet detector train data/obj.data cfg/yolov3_training.cfg /mydrive/yolov3/yolov3_training_last.weights -dont_show
88+
```
89+
To use this, you would:
90+
1. Add a `#` symbol at the beginning of the first training command line to "comment it out" (make it inactive).
91+
2. Remove the `#` symbol from the beginning of the second command line to "uncomment it" (make it active).
92+
3. **Crucially, update the path `/mydrive/yolov3/yolov3_training_last.weights`** to the actual path in your Google Drive where `yolov3_training_last.weights` was saved. For example, if you updated your `.data` file's backup path to `/content/gdrive/MyDrive/Yolo_v3/backup_weights`, the path here would be `/content/gdrive/MyDrive/Yolo_v3/backup_weights/yolov3_training_last.weights`. If you used the default `/content/weight` (temporary), you wouldn't be able to resume after the Colab session ends.
93+
4. Run the cell again.
94+
95+
When you resume, Darknet loads the specified weights and continues training from where it left off, using the same `max_batches` limit defined in the `.cfg` file.
96+
97+
### Under the Hood: The Training Loop
98+
99+
When you run the training command, the Darknet framework orchestrates the entire process. Here's a simplified look at the core steps it performs in a loop:
100+
101+
```mermaid
102+
sequenceDiagram
103+
participant Darknet as Darknet Executable
104+
participant CfgFile as yolov3_training.cfg
105+
participant ObjData as obj.data
106+
participant TrainTxt as train.txt
107+
participant ImagesAndLabels as Training Images + Labels (.txt)
108+
participant ModelWeights as Internal Model Weights
109+
110+
Darknet->>CfgFile: Read network structure & train params (batch, max_batches)
111+
Darknet->>ObjData: Read dataset paths (train.txt, backup)
112+
Darknet->>TrainTxt: Read list of all training image paths
113+
Darknet->>ModelWeights: Load initial weights (darknet53.conv.74 or previous backup)
114+
115+
loop Until max_batches reached
116+
Darknet->>ImagesAndLabels: Select and load a batch of images & their label files
117+
Darknet->>Darknet: Prepare data for GPU
118+
Darknet->>ModelWeights: Feed batch through network (Forward Pass on GPU)
119+
ModelWeights-->>Darknet: Output predictions (boxes, confidences, classes)
120+
Darknet->>ImagesAndLabels: Get true labels for the batch
121+
Darknet->>Darknet: Compare predictions to true labels
122+
Darknet->>Darknet: Calculate the 'loss' (how wrong predictions were)
123+
Darknet->>ModelWeights: Calculate gradients & Update weights (Backward Pass on GPU)
124+
Darknet->>Darknet: Update average loss, print progress
125+
opt If periodic save point or 'last' save
126+
Darknet->>Darknet: Save current ModelWeights to backup path
127+
end
128+
end
129+
Darknet-->>User: Training Finished
130+
```
131+
132+
This loop runs continuously, powered by the GPU, for the number of iterations specified by `max_batches`. Each iteration (batch) allows the model to see more examples and fine-tune its ability to detect your specific objects.
133+
134+
### Analogy Continued
135+
136+
Following our construction analogy:
137+
138+
* Running the train command (`!./darknet detector train ...`): This is like the project manager giving the green light to the construction team (Darknet) to *start building*. They are given the full blueprint (`.cfg`), the list of materials and where to find them (`.data`, `train.txt`, images), and some partially pre-built components (`darknet53.conv.74` weights).
139+
* The Training Output (`Batch #`, `avg`): This is like the project manager getting progress reports from the site – "We finished batch #X, the average error finding objects was Y (and it's going down!), saving current progress..."
140+
* Saving Weights: This is like the construction team periodically creating a detailed snapshot of the building's state and putting it in storage (the `backup` folder) in case work needs to pause and resume later.
141+
* Stopping and Resuming: Stopping is pausing the construction. Resuming is bringing the team back, giving them the *latest* saved snapshot (`yolov3_training_last.weights`), and telling them to continue building towards the final goal (`max_batches`).
142+
143+
The training process is the actual work phase where the neural network model actively learns from your data under the guidance of the Darknet framework, transforming from a blank slate (or a general-purpose pre-trained model) into a specialized detector for your custom objects.
144+
145+
### Conclusion
146+
147+
In this chapter, we initiated the core training process using the Darknet framework. We executed the main training command, understood its components (pointing to the `.data`, `.cfg`, and initial weights files), and learned what to expect in the output (primarily watching the average loss decrease). We also discussed how Darknet saves progress through weights files and how to resume training if needed.
148+
149+
With training underway (or completed!), the next logical step is to use the model you've trained to actually detect objects in new images.
150+
151+
Let's move on to the next steps, which would involve using the trained weights for detection. (As per the project structure provided, the next chapter might cover detection or analysis).
152+
153+
---

0 commit comments

Comments
 (0)