class
ResNetForImageClassification
extends
PretrainedModelClassificationHeadMixinResNetForImageClassification(config: ResNetConfig)ResNet with a global-average-pooled linear classification head.
Combines a ResNet backbone with the standard ImageNet
classification head: an lucid.nn.AdaptiveAvgPool2d to
pool every spatial location into a single feature vector, an
optional lucid.nn.Dropout (controlled by
config.dropout), and a lucid.nn.Linear projection to
config.num_classes logits. When labels are supplied to
forward, a cross-entropy loss is computed and returned
alongside the logits.
Parameters
configResNetConfigArchitecture spec. Use the
*_cls factory functions
(resnet_18_cls, resnet_50_cls, …) to obtain a
paper-cited configuration; pass a custom config to change
num_classes or enable dropout / zero_init_residual.Attributes
configResNetConfigStored copy of the config that built this model.
stem, maxpool, layer1, layer2, layer3, layer4Same backbone components as on
ResNet; see that
class for shape semantics.avgpoolnn.AdaptiveAvgPool2dGlobal average pool collapsing the
H/32 × W/32 feature map
to 1 × 1.classifiernn.ModuleBuilt by
ClassificationHeadMixin._build_classifier —
either a bare lucid.nn.Linear
(dropout == 0.0) or lucid.nn.Sequential wrapping
lucid.nn.Dropout and lucid.nn.Linear.Notes
The classification flow is
where is the global average pool and with . Loss is the standard categorical cross-entropy
computed only when labels is not None — useful for the
common pattern of running inference without a label tensor.
Examples
Run inference on a batch of 224x224 RGB images:
>>> import lucid
>>> from lucid.models.vision.resnet import resnet_50_cls
>>> model = resnet_50_cls()
>>> x = lucid.randn(4, 3, 224, 224)
>>> out = model(x)
>>> out.logits.shape
(4, 1000)
>>> out.loss is None
True
Compute a loss given labels (e.g. during training):
>>> labels = lucid.tensor([0, 1, 2, 3], dtype=lucid.int64)
>>> out = model(x, labels=labels)
>>> out.loss.shape
()Used by 2
Constructors
1Initialise the module and validate the supplied config.
Parameters
configModelConfigMust be an instance of the subclass's declared
config_class.Raises
TypeErrorIf
config_class has not been set on the concrete subclass,
or if config is not an instance of config_class.Instance methods
1forward(x: Tensor, labels: Tensor | None = None)