ImageEmbedder#
- class ImageEmbedder(model='resnet18', weights='DEFAULT', image_size=224, batch_size=64, device=None)[source]#
Bases:
TransformerMixin,BaseEstimatorRepresentation of images as the output of the penultimate layer of a convolutional network of torchvision, e.g. a ResNet or a VGG pretrained on ImageNet.
The images are converted to three channels, resized to
image_sizeand normalized as ImageNet; the last linear layer of the network (the classifier) is removed, so the output is the vector the network classifies, e.g. 512 values forresnet18and 4096 forvgg16.- Parameters:
model (str, default='resnet18') – Name of a classification network of torchvision (
torchvision.models.list_models), e.g.'resnet50','vgg16','efficientnet_b0'.weights (str or None, default='DEFAULT') – Weights of the network, as accepted by
torchvision.models.get_model:'DEFAULT'for the best weights available, None for a network with random weights.image_size (int, default=224) – Side of the square images given to the network.
batch_size (int, default=64) – Number of images processed at once.
device (str, default=None) – Torch device, e.g.
'cpu'or'cuda'. If None, CUDA, Apple MPS or the CPU, the first available.
- Variables:
network (torch.nn.Module) – The network without its last linear layer, in evaluation mode.
n_features_out (int) – Length of the representation of an image.
See also
TextEmbedderthe same for texts.
Notes
The images are arrays of shape (n_images, height, width) for grayscale images, or (n_images, height, width, channels) with 1 or 3 channels (channels last). Integer images are in [0, 255], float images in [0, 1].
The PivotTree paper uses networks trained on each data set: a network pretrained on ImageNet is a general-purpose representation, which can be fine-tuned outside RuleTree and passed as
modelby name only if registered in torchvision.Examples
>>> from sklearn.datasets import load_digits >>> from RuleTree import RuleTreeClassifier >>> from RuleTree.stumps.classification import PivotTreeStumpClassifier >>> from RuleTree.utils.embeddings import ImageEmbedder >>> digits = load_digits() >>> stump = PivotTreeStumpClassifier(embedder=ImageEmbedder("resnet18")) >>> model = RuleTreeClassifier(max_depth=2, base_stumps=stump) >>> model = model.fit(X_img=digits.images / 16, y=digits.target)
- fit(X=None, y=None)[source]#
Load the network (the weights are downloaded the first time). The images are not used.
- Parameters:
X (numpy.ndarray, default=None) – Not used.
y (numpy.ndarray, default=None) – Not used.
- Returns:
self
- Return type:
- transform(X)[source]#
Representation of the images.
- Parameters:
X (numpy.ndarray of shape (n_images, height, width) or (n_images, height, width, channels)) – Images (see the notes of the class).
- Returns:
X_embedded
- Return type:
numpy.ndarray of shape (n_images, n_features_out)