API Reference: Utilities
TensorNets includes a set of powerful utility functions to simplify common tasks like loading data, preprocessing images, and managing model weights.
tensornets.utils
This module contains general-purpose helper functions.
nets.utils.load_img(paths, target_size=None, crop_size=None)
Loads one or more images from file paths.
paths
: A string or a list of strings representing file paths.target_size
: An integer or tuple(height, width)
. Resizes the image to this size before cropping.crop_size
: An integer. Centrally crops the image to this size after resizing.
Returns a NumPy array in NHWC format ([batch, height, width, channels]
).
nets.utils.decode_predictions(preds, top=5)
Decodes the output of an image classification model into a list of human-readable predictions.
preds
: A NumPy array of predictions from a model.top
: An integer specifying the number of top predictions to return.
Returns a list of (class_id, class_name, probability)
tuples.
tensornets.preprocess
This module handles model-specific image preprocessing.
nets.preprocess(scopes, inputs)
Applies the appropriate preprocessing for a given model or list of models.
scopes
: A model tensor, a list of model tensors, or a scope name string.inputs
: A NumPy array of images to be preprocessed.
It automatically detects the model type and applies the correct normalization and channel ordering. This is the recommended way to preprocess images.
The model objects returned by TensorNets have a .preprocess()
method which is a convenient shortcut for this function.
model = nets.ResNet50(inputs)
img = nets.utils.load_img('cat.png')
# This is the recommended way
preprocessed_img = model.preprocess(img)
# This is equivalent
preprocessed_img_alt = nets.preprocess(model, img)
tensornets.pretrained
This module manages the loading of pre-trained weights.
nets.pretrained(scopes)
Assigns pre-trained weights to a model or a list of models within a TensorFlow session.
scopes
: A model tensor or a list of model tensors.
This function should be run inside a tf.Session()
.
model = nets.ResNet50(inputs)
models = [nets.Inception3(inputs), nets.VGG16(inputs)]
with tf.Session() as sess:
# Load weights for a single model
sess.run(model.pretrained())
# Load weights for multiple models
nets.pretrained(models)