Deep Glue API Reference
This section provides an API reference for the main functions in deepglue. In other words, this page directly renders the docstrings from the different modules in deepglue, and provides links to the functions themselves in the code base. It's how you dig into the weeds.
Note Deep Glue is pre-alpha, a rapidly changing work in progress.
Training utilities
deepglue training_utils.py
Functions that are useful for training deep networks, including validation and testing and metrics.
accuracy(outputs, targets, topk=(1,))
Computes the top-k accuracy for classifier predictions.
Calculates how often the true label is within the top-k predictions,
for each value of k specified in topk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outputs
|
Tensor
|
Model predictions of shape (num_samples, num_classes), where each row contains the logits or probabilities for each class. |
required |
targets
|
Tensor
|
The ground truth labels, of shape (num_samples,) or (num_samples, num_classes) if one-hot encoded. |
required |
topk
|
tuple of int
|
A tuple of integers specifying the values of k for which to compute the prediction accuracy. Defaults to (1,). |
(1,)
|
Returns:
| Type | Description |
|---|---|
list of torch.Tensor
|
A list of accuracy values for each specified k in |
Notes
- Adapted from torchvision's accuracy() function (release 0.19.1), which is licensed under the BSD-3 License.
- Original implementation in pytorch/vision/references/classification/utils.py
Source code in deepglue/training_utils.py
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
extract_features(dataloader, feature_extractor, layer, device='cuda')
Extract features from a network layer using a data loader, feature extractor, and specified layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataloader
|
DataLoader
|
DataLoader for the dataset (often configured without shuffling or dropping samples) |
required |
feature_extractor
|
Module
|
The feature extractor model, note this is typically created with
torchvision's |
required |
layer
|
str
|
The name of the layer to extract features from. Must be present in the output of the feature extractor. |
required |
device
|
str
|
The device to use for feature extraction ('cuda' or 'cpu'). Defaults to 'cuda'. |
'cuda'
|
Returns:
| Name | Type | Description |
|---|---|---|
features |
ndarray
|
Extracted features of shape (num_images, num_flattened_features), where |
labels |
ndarray
|
Corresponding ground-truth labels for each image, of shape (num_images,). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the specified layer is not found in the output of the feature extractor. |
Notes
- For large datasets, ensure sufficient memory is available for concatenating feature arrays: they can grow extremely large for large network models.
TODO
- Add optimizations for very large arrays (eg quantization, out-of-core computation with dask and xarray, etc).
Source code in deepglue/training_utils.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 | |
predict_all(model, data_loader, device='cuda')
Make predictions for all batches of data in data loader.
Use the model to generate predictions for all batches from the provided data loader. It returns the predicted class labels, true labels, class probabilities for each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Trained PyTorch model (e.g., ResNet50). |
required |
data_loader
|
DataLoader
|
An iterable that provides batches of input data and their corresponding labels. |
required |
device
|
str
|
The device ('cpu' or 'cuda') on which the model and data are placed. Defaults to 'cuda'. |
'cuda'
|
Returns:
| Name | Type | Description |
|---|---|---|
all_predictions |
Tensor
|
An array of predicted labels for each sample in the dataset, with shape (num_samples,) |
all_labels |
Tensor
|
An array of true labels for each sample in the dataset, with shape (num_samples,) |
all_probabilities |
Tensor
|
A 2D array of shape (num_samples, num_categories) containing the softmax-normalized probabilities for each category: each row represents the predicted probability distribution for a single sample. |
Source code in deepglue/training_utils.py
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
predict_batch(model, image_batch, device='cuda')
Predicts the category probabilities for a batch of images
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Trained PyTorch model (e.g., ResNet50). |
required |
image_batch
|
Tensor
|
A batch of images of shape (batch_size, 3, H, W). |
required |
device
|
str
|
The device ('cpu' or 'cuda') on which the model and data are placed. Defaults to cuda |
'cuda'
|
Returns:
| Name | Type | Description |
|---|---|---|
probabilities |
Tensor
|
Predicted probabilities for each image in the batch. Shape is (batch_size x num_categories) |
TODO
- Change name to predict_sample because this isn't a batch in the conventional sense coming from a data loader, keep the language consistent across the package.
- Have it return predicted 'labels' and actual labels like predict_all does.
Source code in deepglue/training_utils.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
prepare_ordered_data(data_path, transform, num_workers=0, batch_size=4, split_type='valid')
Prepare ordered data loader and correponding image path list for feature extraction or other pipelines that require a full dataset in order.
Generate a list of image paths and a DataLoader for a given dataset split.
The image path and the DataLoader indices are guaranteed to match because both shuffle
and drop_last are set to False, ensuring the data will be accessed in order without
dropping any samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
str or Path
|
Path to the root directory containing the split folders ('train', 'valid', 'test') |
required |
transform
|
torchvision transform (callable)
|
The transformations to apply to each image. |
required |
num_workers
|
int
|
Number of workers for parallel data loading. Higher values improve performance during feature extraction but may lead to multiprocessing issues on some platforms. Defaults to 0 (no multiprocessing). |
0
|
batch_size
|
int
|
Batch size for the DataLoader. Larger values improve feature extraction speed but requires more memory. Defaults to 4. |
4
|
split_type
|
str
|
The split folder to sample from ('train', 'valid', 'test'). Defaults to 'train'. |
'valid'
|
Returns:
| Name | Type | Description |
|---|---|---|
image_paths |
list of str
|
A list of file paths to the images in the dataset split, in the same order as the DataLoader batches. |
ordered_loader |
DataLoader
|
A DataLoader for the ordered dataset split, configured to not shuffle data and to include all samples. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified data paths do not exist. |
Notes
- Designed for feature extraction workflows where maintaining the correspondence between image file paths and DataLoader batches is critical.
- For large datasets, consider increasing
num_workersandbatch_sizefor better performance.
Source code in deepglue/training_utils.py
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 | |
train_and_validate(model, train_data_loader, valid_data_loader, loss_function, optimizer, device, topk=(1, 5), epochs=25)
Train and validate a model for a given number of epochs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
torch model
|
The neural network model to be trained and validated. |
required |
train_data_loader
|
DataLoader
|
An iterable that provides the training data batches. |
required |
valid_data_loader
|
DataLoader
|
An iterable that provides the batches for validation data set |
required |
loss_function
|
callable
|
The loss function to compute the loss (e.g., CrossEntropyLoss). |
required |
optimizer
|
Optimizer
|
The optimizer used to update model parameters during training (e.g., Adam, SGD). |
required |
device
|
str
|
The device ('cpu' or 'cuda') on which the model and data are placed. |
required |
topk
|
A tuple specifying which top-k accuracies to calculate. Defaults to (1,5) |
(1, 5)
|
|
epochs
|
int
|
Number of epochs to run. Defaults to 25. |
25
|
Returns:
| Name | Type | Description |
|---|---|---|
model |
Module
|
The trained model after the completion of training. |
history |
dict
|
A dictionary containing training and validation loss and top-k accuracies per epoch. |
Source code in deepglue/training_utils.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
train_one_epoch(model, train_data_loader, loss_function, optimizer, device, topk=(1, 5))
Trains the model for one epoch using the provided training data loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
torch model
|
The neural network model to be trained. |
required |
train_data_loader
|
DataLoader
|
An iterable that provides the training data batches. |
required |
loss_function
|
callable
|
The loss function to compute the loss (e.g., CrossEntropyLoss). |
required |
optimizer
|
Optimizer
|
The optimizer used to update model parameters (e.g., Adam, SGD). |
required |
device
|
str
|
The device ('cpu' or 'cuda') on which the model and data are to be placed. |
required |
topk
|
A tuple specifying which top-k accuracies to calculate. Defaults to (1,5) |
(1, 5)
|
Returns:
| Name | Type | Description |
|---|---|---|
epoch_loss |
float
|
The average loss over all samples in the epoch. |
epoch_topk_acc |
list of floats
|
A list of average top-k accuracies over all samples in the epoch. |
Notes
The function logs progress using the logging module. Set your loggers to 'debug' to see progress.
Source code in deepglue/training_utils.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
validate_one_epoch(model, valid_data_loader, loss_function, device, topk=(1, 5))
Validates the model for one epoch using the provided validation data loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
torch model
|
The neural network model to be validated. |
required |
valid_data_loader
|
DataLoader
|
An iterable that provides the batches for validation data set |
required |
loss_function
|
callable
|
The loss function to compute the loss (e.g., CrossEntropyLoss). |
required |
device
|
str
|
The device ('cpu' or 'cuda') on which the model and data are placed. |
required |
topk
|
A tuple specifying which top-k accuracies to calculate. Defaults to (1,5) |
(1, 5)
|
Returns:
| Name | Type | Description |
|---|---|---|
epoch_loss |
float
|
The average loss over all samples in the validation epoch. |
epoch_topk_acc |
list of floats
|
A list of average top-k accuracies over all samples in the epoch. |
Notes
Runs in evaluation mode (model.eval()) and gradient calculations are disabled.
Source code in deepglue/training_utils.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
Plot utilities
deepglue plot_utils.py
Module includes functions that are useful for plotting/visualization during different deep learning tasks
convert_for_plotting(tensor)
Convert torch tensor image (typically float CxHxW) to a format suitable for standard plotting libraries (uint8 HxWxC).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
The input tensor image. Expected shape: (C, H, W). Typically a float, often not in [0, 1] range. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A uint8 tensor image scaled to [0, 255] for plotting and dims (H,W,C) |
Source code in deepglue/plot_utils.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
create_embeddable_image(image_path, size=(50, 50), quality=50)
Converts an image to a base64-encoded string for embedding in HTML.
Loads an image from disk, resizes it, and converts it to a specified format (default is JPEG). The processed image is then base64-encoded and returned as a string that can be embedded in HTML or visualized interactively using tools like Bokeh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str or Path
|
Path to the input image file. |
required |
size
|
tuple of int
|
Desired size for the resized image as (width, height). Defaults to (50, 50). |
(50, 50)
|
format
|
str
|
Image format for saving. Supported formats include 'JPEG' and 'PNG'. Defaults to 'JPEG'. |
required |
quality
|
int
|
Compression quality for the image Valid values are between 1 (worst) and 95 (best). Defaults to 50. |
50
|
Returns:
| Type | Description |
|---|---|
str
|
A Base64-encoded string representing the processed image, ready for embedding. |
Notes
- Adapted from umap example at https://umap-learn.readthedocs.io/en/latest/basic_usage.html
Source code in deepglue/plot_utils.py
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | |
plot_batch(batch_images, batch_targets, category_map, max_to_plot=32)
Plots a batch of images, and their corresponding target categories, from a DataLoader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_images
|
Tensor
|
A tensor containing a batch of images with shape |
required |
batch_targets
|
Tensor
|
A tensor containing the target labels for the batch, with shape |
required |
category_map
|
dict
|
A dictionary mapping category indices (as strings) to their human-readable
labels, e.g., |
required |
max_to_plot
|
int
|
The maximum number of images to plot from the batch. Defaults to 32. |
32
|
cmap
|
str
|
The colormap to use for displaying images. Defaults to 'gray'. |
required |
Returns:
| Type | Description |
|---|---|
None
|
Displays a grid of images with their corresponding labels. |
Notes
- Images are converted to grayscale.
- If batch size is smaller than
max_to_plot, all images in batch will be plotted.
Source code in deepglue/plot_utils.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
plot_interactive_projection(features_2d, labels, image_paths, category_map, predictions=None, title='Feature Projection', image_size=(50, 50), plot_size=800, legend_location=None, show_in_notebook=True)
Create an interactive Bokeh plot for any low-dimensional projection of features corresponding to images.
Create an interactive plot of a 2D projection of features extracted from images, such as those obtained using dimensionality reduction techniques like UMAP, PCA, or t-SNE. When you hover over scatter point, it shows the original image corresponding to the point in the 2d space. If you provide predictions, it will show the incorrect predictions as an X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features_2d
|
array - like
|
2D array of features obtained after dimensionality reduction (num_samples, 2). |
required |
labels
|
list
|
List of integer labels for the data points (len num_samples). |
required |
image_paths
|
list
|
List of file paths to the images corresponding to the features (len num_samples). |
required |
category_map
|
dict
|
A mapping of category indices (as strings) to their respective labels. Example: {'0': 'cat', '1': 'dog'}. |
required |
predictions
|
array - like
|
Predicted labels for the data points (len num_samples). Defaults to None. |
None
|
title
|
str
|
Title of the plot. Defaults to 'Feature Projection'. |
'Feature Projection'
|
image_size
|
tuple
|
Size of the images shown in plot when you hover over points (width, height). Defaults to (50, 50). |
(50, 50)
|
plot_size
|
int
|
Size of the plot (width and height in pixels). Defaults to 800. |
800
|
legend_location
|
Location of the legend. Defaults to None which puts it in default location. Options include 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'top', 'bottom', 'left', 'right','center' |
None
|
|
show_in_notebook
|
bool
|
If True, display the plot inline in a Jupyter Notebook. If False, open the plot in a new browser tab (projection_plot.html). Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
None
|
Displays the interactive plot. |
Source code in deepglue/plot_utils.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | |
plot_prediction_grid(images, probability_matrix, true_categories, category_map, top_n=5, figsize_per_plot=(2, 3), logscale=True)
Plots a grid of classifier prediction visualizations.
Each visualization in the grid contains the image on the left , plotted using dg.plot_prediction_image() and bar plot of top_n category probabilities on the right, plotting using dg.visualize_prediction_probs()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
Shape num_predictions x 3 x H x W of images to be classified |
required |
probability_matrix
|
Tensor
|
Torch tensor w/shape num predictions x num categories Each row corresponds to image and contains classifier probabilities for each category. |
required |
true_categories
|
list of str
|
Length num_predictions list of correct labels for each prediction (e.g., ['cat', 'dog'...] |
required |
category_map
|
dict
|
A mapping of category indices (as strings) to their respective labels. Example: {'0': 'cat', '1': 'dog'}. |
required |
top_n
|
int
|
The top n class probabilities to show in bar plot, default is 5. |
5
|
figsize_per_plot
|
tuple
|
Size of each (image + bar plot) pair in inches. Default is (3, 3). |
(2, 3)
|
logscale
|
bool
|
If True, the bar plot uses a logarithmic scale. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
fig |
Figure
|
The figure object containing the full grid of prediction plots. |
axes |
np.ndarray of matplotlib.axes.Axes
|
Array of axes objects arranged in a grid |
Note
Inspired by visualization created by the Nuevo Foundation: https://workshops.nuevofoundation.org/python-tensorflow/plotting_model/
Source code in deepglue/plot_utils.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
plot_prediction_image(tensor, probabilities, category_map, true_label=None, ax=None, figsize=(2.5, 2.5))
Plot classifier prediction: displays image with true label on top and estimate on bottom with probability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
The input image tensor (CxHxW) or 1xCxHxW |
required |
probabilities
|
Tensor
|
Prediction probabilities for each category (1D tensor). |
required |
category_map
|
dict
|
A mapping of category indices (as strings) to their respective labels. Example: {'0': 'cat', '1': 'dog'}. |
required |
true_label
|
str
|
The actual category label of the image, if known (e.g., 'dog'). Default is None. |
None
|
axes
|
Axes
|
Axes object for plot. If None, new axes are created. Default is None. |
required |
figsize
|
tuple
|
Size of the figure in inches. Default is (2.5, 2.5). |
(2.5, 2.5)
|
Returns:
| Name | Type | Description |
|---|---|---|
fig |
Figure
|
The figure object for further customization or saving. |
axes |
Axes
|
The image axis object |
Source code in deepglue/plot_utils.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
plot_prediction_probs(probabilities, category_map, true_label=None, top_n=5, logscale=True, ax=None, figsize=(3, 2.5), bar_color='skyblue')
Plot classifier prediction probabilities: bar plot of top N category probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probabilities
|
Tensor
|
Prediction probabilities for each category (1D tensor). |
required |
category_map
|
dict
|
A mapping of category indices (as strings) to their respective labels. Example: {'0': 'cat', '1': 'dog'}. |
required |
true_label
|
str
|
The actual category label, if known (e.g., 'dog'). Default is None. |
None
|
top_n
|
int
|
The top n class probabilities to display from the classifier, default is 5. |
5
|
logscale
|
bool
|
If True, the bar plot uses a logarithmic scale. Default is True. |
True
|
axes
|
Axes
|
Axes object for plot. If None, new axes are created. Default is None. |
required |
figsize
|
tuple
|
Size of the figure in inches. Default is (2.5, 2.5). |
(3, 2.5)
|
bar_color
|
str
|
Color for the bars in the bar plot. Default is 'skyblue'. |
'skyblue'
|
Returns:
| Name | Type | Description |
|---|---|---|
fig |
Figure
|
The figure object for further customization or saving. |
axes |
Axes
|
The bar plot axis object |
Source code in deepglue/plot_utils.py
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
plot_random_category_sample(data_path, category, split_type='train', num_to_plot=16)
Plots a random selection of images from a specific category within a data split.
Assumes a directory structure where images are stored in category-specific subdirectories under split folders (e.g., 'train', 'valid', 'test'):
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
str or Path
|
The path to the root directory containing the split folders ('train', 'valid', 'test'). |
required |
category
|
str
|
The name of the category from which to plot images (e.g., 'cat') |
required |
split_type
|
str
|
The split folder to pull images from ('train', 'valid', 'test'). Defaults to 'train'. |
'train'
|
num_to_plot
|
int
|
The number of images to plot. Defaults to 16. If it exceeds the available number of images, a warning will be issued and all available images will be plotted. |
16
|
Returns:
| Name | Type | Description |
|---|---|---|
fig |
Figure
|
The figure object containing the subplots. |
axes |
array of matplotlib.axes
|
An array of matplotlib Axes objects, one for each image subplot. |
Source code in deepglue/plot_utils.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
plot_random_sample(data_path, category_map, split_type='train', num_to_plot=16)
Plots random image samples from a specified data split.
Assumes a directory structure where images are stored in category-specific subdirectories inside the split folders ('train', 'valid', 'test').
data_path/
train/
cat/
dog/
valid/
cat/
dog/
test/
cat/
dog/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
str or Path
|
The path to the root directory containing the split folders ('train', 'valid', 'test'). |
required |
category_map
|
dict
|
A dictionary mapping category indices (as strings) to their human-readable
labels, e.g., |
required |
split_type
|
str
|
The split folder to pull images from ('train', 'valid', 'test'). Defaults to 'train'. |
'train'
|
num_to_plot
|
int
|
Number of images to plot. Defaults to 16. |
16
|
Returns:
| Name | Type | Description |
|---|---|---|
fig |
Figure
|
The figure object containing the subplots |
axes |
array of matplotlib.axes
|
An array of matplotlib Axes objects, one for each image subplot. |
Source code in deepglue/plot_utils.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
plot_transformed(original_image, transform, cmap=None, num_to_plot=4)
Plot the original image and pytorch transformations applied to it.
original_image : 2d array-like image The original image to be transformed. Can be tensor or numpy/PIL or other array. transform : pytorch transform callable A transformation function (or series of transformations) to apply to the original image. The function should accept an image and return a transformed tensor. cmap : str, optional Colormap to use for displaying greyscale images. Set to None for color images. num_transforms : int, optional The number of transformed images to generate and display, in addition to original image. Defaults to 4.
Returns:
| Name | Type | Description |
|---|---|---|
fig |
Figure
|
The figure object containing the plots. |
axes |
array of matplotlib.axes
|
The axes array containing the individual image subplots. |
Notes
- The first image displayed is the original, and subsequent images are transformed versions.
Source code in deepglue/plot_utils.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
File Utilities
deepglue file_utils.py
Module includes functions that are useful for wrangling directories and files.
count_by_category(data_path)
Calculates the total number of images for each category across all splits.
Traverses the train, valid, and test folders and aggregates image counts for each category. This can be useful for identifying category imbalances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
Path
|
The path to the parent directory containing the 'train', 'valid', and 'test' folders. They each contain the same category-specific subdirectories. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
num_per_category |
dict
|
A dictionary where keys are category names and values are the total number of images in each category. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If any of the specified split directories ('train', 'valid', 'test') do not exist at the given path. |
Source code in deepglue/file_utils.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
count_by_split(data_path)
Calculates the total number of images in train, test, and validation splits, regardless of categories.
This function directly traverses the 'train', 'valid', and 'test' folders and counts all image files, providing the total number of samples in each split without considering category distinctions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
Path
|
The path to the directory containing the 'train', 'valid', and 'test' folders. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
num_per_split |
dict
|
A dictionary with keys 'train', 'valid', and 'test', each containing the total number of samples in each split, regardless of category. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If any of the specified split directories ('train', 'valid', 'test') do not exist at the given path. |
Source code in deepglue/file_utils.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
count_category_by_split(data_path)
Counts the number of images in each category within train, validation, and test splits.
Assumes a directory structure where images are stored in category-specific subdirectories under 'train', 'valid', and 'test' folders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
Path
|
The path to the directory containing the 'train', 'valid', and 'test' folders. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
num_category_per_split |
dict
|
A nested dictionary with keys 'train', 'valid', and 'test', each containing a sub-dictionary where the keys are category names and the values are the counts of images in each category. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If any of the 'train', 'valid', or 'test' directories do not exist at the specified path. |
Source code in deepglue/file_utils.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | |
create_project(projects_dir, project_name)
Creates a minimal project directory structure within the project parent directory:
projects_dir/
project_name/
data/
models/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
projects_dir
|
str or Path
|
Path to the project parent directory. |
required |
project_name
|
str
|
name of the project (must be a valid directory name: avoid spaces and other weird things) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
project_dir |
Path
|
Path to the project directory that was created in projects_dir |
data_dir |
Path
|
Path to the data directory in project_dir |
models_dir |
Path
|
Path to the models directory in the project_dir |
TODO
consider using pathvalidate to throw error if project_name is invalid
Source code in deepglue/file_utils.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
create_subdirs(parent_dir, subdirs)
Create subdirectories within a specified parent directory, unless they already exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent_dir
|
The path to the parent directory where subdirectories will be created |
required | |
subdirs
|
List of subdirectory names to create within the parent directory. If a single string is provided, will be converted to a list |
required |
Returns:
| Name | Type | Description |
|---|---|---|
new_paths |
list of Path
|
A list of path objects to the newly created subdirectories |
Example
create_subdirs(Path("path/to/parent"), ["subdir1", "subdir2"]) [Path('/path/to/parent/subdir1'), Path('/path/to/parent/subdir2')]
Source code in deepglue/file_utils.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | |
load_images_for_model(image_paths, transform)
Given a list of image paths, returns a tensor suitable for model input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_paths
|
list of str or Paths
|
List of image file paths. |
required |
transform
|
torchvision transform (callable)
|
The transformations to apply to each image. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A batch of images as a tensor of shape (len(image_paths), 3, H, W). |
Source code in deepglue/file_utils.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
sample_random_images(data_path, category_map, num_images=1, split_type='train', category=None)
Randomly sample image paths from a dataset with a standard categorical directory structure.
Assumes a directory structure where images are stored in category-specific subdirectories inside the split folders ('train', 'valid', 'test').
data_path/
train/
cat/
dog/
valid/
cat/
dog/
test/
cat/
dog/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
str or Path
|
Path to the root directory containing the split folders ('train', 'valid', 'test') |
required |
category_map
|
dict
|
Dictionary mapping category index (as string) to category name: {'0': 'dog', '1': 'cat'} |
required |
num_images
|
int
|
Number of image paths to sample, by default 1. |
1
|
split_type
|
str
|
The split folder to sample from ('train', 'valid', 'test'). Defaults to 'train'. |
'train'
|
category
|
str
|
If specified, only images from this category will be sampled. When default of None is chosen, will select randomly across all categories. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
sampled_paths |
list
|
len num_images list of paths to images |
sampled_categories |
list
|
len num_images list of corresponding categories |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified split or category path does not exist. |
Notes
- Assumes that each split folder contains only category subdirectories.
- If
num_imagesexceeds the total available images, all images will be returned, and a warning will be logged.
Source code in deepglue/file_utils.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
split_dataset(source_dir, target_dir, splits=(0.7, 0.15, 0.15), shuffle=True)
Splits a dataset organized by category folders into train/valid/test folders.
Copies images from a flat category structure (e.g. target_dir/ cat/, dog/, etc.) into a canonical deep learning format with separate splits:
target_dir/
train/
cat/
dog/
valid/
cat/
dog/
test/
cat/
dog/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_dir
|
str or Path
|
Path to the folder containing category subfolders (e.g. cat/, dog/). |
required |
target_dir
|
str or Path
|
Path where the split dataset should be created. |
required |
splits
|
tuple of 3 floats
|
Tuple indicating proportions of (train, valid, test) splits. Values must sum to 1.0. Defaults to (0.7, 0.15, 0.15). |
(0.7, 0.15, 0.15)
|
shuffle
|
bool
|
Whether to shuffle images before splitting within a category. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
counts |
dict
|
A nested dictionary showing the number of images per category in each split Example: { 'train': {'cat': 140, 'dog': 200}, 'valid': {'cat': 30, 'dog': 40}, 'test': {'cat': 30, 'dog': 35} } |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source directory does not exist. |
Source code in deepglue/file_utils.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | |