class_docstr: Visual representations using a torchvision model.
  
  ---
  name: Visual
docstr: Initialize the representations.
  
  :param images:
      the images, either as tensors, or paths to image files.
  :param encoder:
      the encoder to use. If given as a string, lookup in :module:`torchvision.models`
  :param layer_name:
      the model's layer name to use for extracting the features, cf.
      :func:`torchvision.models.feature_extraction.create_feature_extractor`
  :param max_id:
      the number of representations. If given, it must match the number of images.
  :param shape:
      the shape of an individual representation. If provided, it must match the encoder output dimension
  :param transforms:
      transformations to apply to the images. Notice that stochastic transformations will result in
      stochastic representations, too.
  :param encoder_kwargs:
      additional keyword-based parameters passed to encoder upon instantiation.
  :param batch_size:
      the batch size to use during encoding
  :param trainable:
      whether the encoder should be trainable
  :param kwargs:
      additional keyword-based parameters passed to :meth:`Representation.__init__`.
  
  :raises ValueError:
      if `max_id` is provided and does not match the number of images
docstr_tok: ["Initialize","the","representations",".",":","param","images",":","the","images",",","either","as","tensors",",","or","paths","to","image","files",".",":","param","encoder",":","the","encoder","to","use",".","If","given","as","a","string",",","lookup","in",":","module",":","`","torchvision.models","`",":","param","layer_name",":","the","model","'s","layer","name","to","use","for","extracting","the","features",",","cf",".",":","func",":","`","torchvision.models.feature_extraction.create_feature_extractor","`",":","param","max_id",":","the","number","of","representations",".","If","given",",","it","must","match","the","number","of","images",".",":","param","shape",":","the","shape","of","an","individual","representation",".","If","provided",",","it","must","match","the","encoder","output","dimension",":","param","transforms",":","transformations","to","apply","to","the","images",".","Notice","that","stochastic","transformations","will","result","in","stochastic","representations",",","too",".",":","param","encoder_kwargs",":","additional","keyword-based","parameters","passed","to","encoder","upon","instantiation",".",":","param","batch_size",":","the","batch","size","to","use","during","encoding",":","param","trainable",":","whether","the","encoder","should","be","trainable",":","param","kwargs",":","additional","keyword-based","parameters","passed","to",":","meth",":","`","Representation.__init__","`",".",":","raises","ValueError",":","if","`","max_id","`","is","provided","and","does","not","match","the","number","of","images"]
code: def __init__(
      self,
      images: Sequence,
      encoder: Union[str, torch.nn.Module],
      layer_name: str,
      max_id: Optional[int] = None,
      shape: Optional[OneOrSequence[int]] = None,
      transforms: Optional[Sequence] = None,
      encoder_kwargs: OptionalKwargs = None,
      batch_size: int = 32,
      trainable: bool = True,
      **kwargs,
  ):
      """
      Initialize the representations.
  
      :param images:
          the images, either as tensors, or paths to image files.
      :param encoder:
          the encoder to use. If given as a string, lookup in :module:`torchvision.models`
      :param layer_name:
          the model's layer name to use for extracting the features, cf.
          :func:`torchvision.models.feature_extraction.create_feature_extractor`
      :param max_id:
          the number of representations. If given, it must match the number of images.
      :param shape:
          the shape of an individual representation. If provided, it must match the encoder output dimension
      :param transforms:
          transformations to apply to the images. Notice that stochastic transformations will result in
          stochastic representations, too.
      :param encoder_kwargs:
          additional keyword-based parameters passed to encoder upon instantiation.
      :param batch_size:
          the batch size to use during encoding
      :param trainable:
          whether the encoder should be trainable
      :param kwargs:
          additional keyword-based parameters passed to :meth:`Representation.__init__`.
  
      :raises ValueError:
          if `max_id` is provided and does not match the number of images
      """
      _ensure_vision(self, models)
      self.images = VisionDataset(images=images, transforms=transforms)
  
      if isinstance(encoder, str):
          cls = getattr(models, encoder)
          encoder = cls(encoder_kwargs or {})
  
      pool = functools.partial(torch.mean, dim=(-1, -2))
  
      encoder = models.feature_extraction.create_feature_extractor(
          model=encoder, return_nodes={layer_name: "feature"}
      )
  
      # infer shape
      with torch.inference_mode():
          encoder.eval()
          shape_ = self._encode(
              images=self.images[0].unsqueeze(dim=0),
              encoder=encoder,
              pool=pool,
          ).shape[1:]
      shape = ShapeError.verify(shape=shape_, reference=shape)
      if max_id is None:
          max_id = len(images)
      elif len(images) != max_id:
          raise ValueError(
              f"Inconsistent max_id={max_id} and len(images)={len(images)}. In case there are not images for all "
              f"IDs, you may consider using BackfillRepresentation.",
          )
      super().__init__(max_id=max_id, shape=shape, **kwargs)
  
      self.encoder = encoder
      self.pool = pool
      self.batch_size = batch_size or self.max_id
      self.encoder.train(trainable)
      self.encoder.requires_grad_(trainable)
      self.trainable = trainable
  
imports: import functools
  import pathlib
  from typing import Any, Callable, Optional, Sequence, Union
  import torch
  import torch.nn
  import torch.utils.data
  from class_resolver import OptionalKwargs
  from docdata import parse_docdata
  from .representation import BackfillRepresentation, Representation
  from .utils import ShapeError, WikidataCache
  from ..datasets import Dataset
  from ..triples import TriplesFactory
  from ..typing import OneOrSequence
label_desc: Use image node_id 1 to create a new VisualRepresentation object from inherited base classes: Representation with example: obj = VisualRepresentation(images, encoder, layer_name, max_id, shape, transforms, encoder_kwargs, batch_size, trainable)