RegressionLearnerConfig#

Note

All Configs are derived from rastervision.pipeline.config.Config, which itself is a pydantic Model.

pydantic model RegressionLearnerConfig[source]#

Configure a RegressionLearner.

Show JSON schema
{
   "title": "RegressionLearnerConfig",
   "description": "Configure a :class:`.RegressionLearner`.",
   "type": "object",
   "properties": {
      "model": {
         "$ref": "#/definitions/RegressionModelConfig"
      },
      "solver": {
         "$ref": "#/definitions/SolverConfig"
      },
      "data": {
         "$ref": "#/definitions/DataConfig"
      },
      "eval_train": {
         "title": "Eval Train",
         "description": "If True, runs final evaluation on training set (in addition to validation set). Useful for debugging.",
         "default": false,
         "type": "boolean"
      },
      "save_model_bundle": {
         "title": "Save Model Bundle",
         "description": "If True, saves a model bundle at the end of training which is zip file with model and this LearnerConfig which can be used to make predictions on new images at a later time.",
         "default": true,
         "type": "boolean"
      },
      "log_tensorboard": {
         "title": "Log Tensorboard",
         "description": "Save Tensorboard log files at the end of each epoch.",
         "default": true,
         "type": "boolean"
      },
      "run_tensorboard": {
         "title": "Run Tensorboard",
         "description": "run Tensorboard server during training",
         "default": false,
         "type": "boolean"
      },
      "output_uri": {
         "title": "Output Uri",
         "description": "URI of where to save output",
         "type": "string"
      },
      "save_all_checkpoints": {
         "title": "Save All Checkpoints",
         "description": "If True, all checkpoints would be saved. The latest checkpoint would be saved as `last-model.pth`. The checkpoints prior to last epoch are stored as `model-ckpt-epoch-{N}.pth` where `N` is the epoch number.",
         "default": false,
         "type": "boolean"
      },
      "type_hint": {
         "title": "Type Hint",
         "default": "regression_learner",
         "enum": [
            "regression_learner"
         ],
         "type": "string"
      }
   },
   "required": [
      "data"
   ],
   "additionalProperties": false,
   "definitions": {
      "Backbone": {
         "title": "Backbone",
         "description": "An enumeration.",
         "enum": [
            "alexnet",
            "densenet121",
            "densenet169",
            "densenet201",
            "densenet161",
            "googlenet",
            "inception_v3",
            "mnasnet0_5",
            "mnasnet0_75",
            "mnasnet1_0",
            "mnasnet1_3",
            "mobilenet_v2",
            "resnet18",
            "resnet34",
            "resnet50",
            "resnet101",
            "resnet152",
            "resnext50_32x4d",
            "resnext101_32x8d",
            "wide_resnet50_2",
            "wide_resnet101_2",
            "shufflenet_v2_x0_5",
            "shufflenet_v2_x1_0",
            "shufflenet_v2_x1_5",
            "shufflenet_v2_x2_0",
            "squeezenet1_0",
            "squeezenet1_1",
            "vgg11",
            "vgg11_bn",
            "vgg13",
            "vgg13_bn",
            "vgg16",
            "vgg16_bn",
            "vgg19_bn",
            "vgg19"
         ]
      },
      "ExternalModuleConfig": {
         "title": "ExternalModuleConfig",
         "description": "Config describing an object to be loaded via Torch Hub.",
         "type": "object",
         "properties": {
            "uri": {
               "title": "Uri",
               "description": "Local uri of a zip file, or local uri of a directory,or remote uri of zip file.",
               "minLength": 1,
               "type": "string"
            },
            "github_repo": {
               "title": "Github Repo",
               "description": "<repo-owner>/<repo-name>[:tag]",
               "pattern": ".+/.+",
               "type": "string"
            },
            "name": {
               "title": "Name",
               "description": "Name of the folder in which to extract/copy the definition files.",
               "minLength": 1,
               "type": "string"
            },
            "entrypoint": {
               "title": "Entrypoint",
               "description": "Name of a callable present in hubconf.py. See docs for torch.hub for details.",
               "minLength": 1,
               "type": "string"
            },
            "entrypoint_args": {
               "title": "Entrypoint Args",
               "description": "Args to pass to the entrypoint. Must be serializable.",
               "default": [],
               "type": "array",
               "items": {}
            },
            "entrypoint_kwargs": {
               "title": "Entrypoint Kwargs",
               "description": "Keyword args to pass to the entrypoint. Must be serializable.",
               "default": {},
               "type": "object"
            },
            "force_reload": {
               "title": "Force Reload",
               "description": "Force reload of module definition.",
               "default": false,
               "type": "boolean"
            },
            "type_hint": {
               "title": "Type Hint",
               "default": "external-module",
               "enum": [
                  "external-module"
               ],
               "type": "string"
            }
         },
         "required": [
            "entrypoint"
         ],
         "additionalProperties": false
      },
      "RegressionModelConfig": {
         "title": "RegressionModelConfig",
         "description": "Configure a regression model.",
         "type": "object",
         "properties": {
            "backbone": {
               "description": "The torchvision.models backbone to use.",
               "default": "resnet18",
               "allOf": [
                  {
                     "$ref": "#/definitions/Backbone"
                  }
               ]
            },
            "pretrained": {
               "title": "Pretrained",
               "description": "If True, use ImageNet weights. If False, use random initialization.",
               "default": true,
               "type": "boolean"
            },
            "init_weights": {
               "title": "Init Weights",
               "description": "URI of PyTorch model weights used to initialize model. If set, this supersedes the pretrained option.",
               "type": "string"
            },
            "load_strict": {
               "title": "Load Strict",
               "description": "If True, the keys in the state dict referenced by init_weights must match exactly. Setting this to False can be useful if you just want to load the backbone of a model.",
               "default": true,
               "type": "boolean"
            },
            "external_def": {
               "title": "External Def",
               "description": "If specified, the model will be built from the definition from this external source, using Torch Hub.",
               "allOf": [
                  {
                     "$ref": "#/definitions/ExternalModuleConfig"
                  }
               ]
            },
            "extra_args": {
               "title": "Extra Args",
               "description": "Other implementation-specific args that might be useful for constructing the default model. This is ignored if using an external model.",
               "default": {},
               "type": "object"
            },
            "type_hint": {
               "title": "Type Hint",
               "default": "regression_model",
               "enum": [
                  "regression_model"
               ],
               "type": "string"
            },
            "output_multiplier": {
               "title": "Output Multiplier",
               "type": "array",
               "items": {
                  "type": "number"
               }
            }
         },
         "additionalProperties": false
      },
      "SolverConfig": {
         "title": "SolverConfig",
         "description": "Config related to solver aka optimizer.",
         "type": "object",
         "properties": {
            "lr": {
               "title": "Lr",
               "description": "Learning rate.",
               "default": 0.0001,
               "exclusiveMinimum": 0,
               "type": "number"
            },
            "num_epochs": {
               "title": "Num Epochs",
               "description": "Number of epochs (ie. sweeps through the whole training set).",
               "default": 10,
               "exclusiveMinimum": 0,
               "type": "integer"
            },
            "sync_interval": {
               "title": "Sync Interval",
               "description": "The interval in epochs for each sync to the cloud.",
               "default": 1,
               "exclusiveMinimum": 0,
               "type": "integer"
            },
            "batch_sz": {
               "title": "Batch Sz",
               "description": "Batch size.",
               "default": 32,
               "exclusiveMinimum": 0,
               "type": "integer"
            },
            "one_cycle": {
               "title": "One Cycle",
               "description": "If True, use triangular LR scheduler with a single cycle across all epochs with start and end LR being lr/10 and the peak being lr.",
               "default": true,
               "type": "boolean"
            },
            "multi_stage": {
               "title": "Multi Stage",
               "description": "List of epoch indices at which to divide LR by 10.",
               "default": [],
               "type": "array",
               "items": {}
            },
            "class_loss_weights": {
               "title": "Class Loss Weights",
               "description": "Class weights for weighted loss.",
               "type": "array",
               "items": {
                  "type": "number"
               }
            },
            "ignore_class_index": {
               "title": "Ignore Class Index",
               "description": "If specified, this index is ignored when computing the loss. See pytorch documentation for nn.CrossEntropyLoss for more details. This can also be negative, in which case it is treated as a negative slice index i.e. -1 = last index, -2 = second-last index, and so on.",
               "type": "integer"
            },
            "external_loss_def": {
               "title": "External Loss Def",
               "description": "If specified, the loss will be built from the definition from this external source, using Torch Hub.",
               "allOf": [
                  {
                     "$ref": "#/definitions/ExternalModuleConfig"
                  }
               ]
            },
            "type_hint": {
               "title": "Type Hint",
               "default": "solver",
               "enum": [
                  "solver"
               ],
               "type": "string"
            }
         },
         "additionalProperties": false
      },
      "PlotOptions": {
         "title": "PlotOptions",
         "description": "Config related to plotting.",
         "type": "object",
         "properties": {
            "transform": {
               "title": "Transform",
               "description": "An Albumentations transform serialized as a dict that will be applied to each image before it is plotted. Mainly useful for undoing any data transformation that you do not want included in the plot, such as normalization. The default value will shift and scale the image so the values range from 0.0 to 1.0 which is the expected range for the plotting function. This default is useful for cases where the values after normalization are close to zero which makes the plot difficult to see.",
               "default": {
                  "__version__": "1.4.1",
                  "transform": {
                     "__class_fullname__": "rastervision.pytorch_learner.utils.utils.MinMaxNormalize",
                     "always_apply": false,
                     "p": 1.0,
                     "min_val": 0.0,
                     "max_val": 1.0,
                     "dtype": 5
                  }
               },
               "type": "object"
            },
            "channel_display_groups": {
               "title": "Channel Display Groups",
               "description": "Groups of image channels to display together as a subplot when plotting the data and predictions. Can be a list or tuple of groups (e.g. [(0, 1, 2), (3,)]) or a dict containing title-to-group mappings (e.g. {\"RGB\": [0, 1, 2], \"IR\": [3]}), where each group is a list or tuple of channel indices and title is a string that will be used as the title of the subplot for that group.",
               "anyOf": [
                  {
                     "type": "object",
                     "additionalProperties": {
                        "type": "array",
                        "items": {
                           "type": "integer",
                           "minimum": 0
                        }
                     }
                  },
                  {
                     "type": "array",
                     "items": {
                        "type": "array",
                        "items": {
                           "type": "integer",
                           "minimum": 0
                        }
                     }
                  }
               ]
            },
            "type_hint": {
               "title": "Type Hint",
               "default": "plot_options",
               "enum": [
                  "plot_options"
               ],
               "type": "string"
            }
         },
         "additionalProperties": false
      },
      "DataConfig": {
         "title": "DataConfig",
         "description": "Config related to dataset for training and testing.",
         "type": "object",
         "properties": {
            "class_names": {
               "title": "Class Names",
               "description": "Names of classes.",
               "default": [],
               "type": "array",
               "items": {
                  "type": "string"
               }
            },
            "class_colors": {
               "title": "Class Colors",
               "description": "Colors used to display classes. Can be color 3-tuples in list form.",
               "type": "array",
               "items": {
                  "anyOf": [
                     {
                        "type": "string"
                     },
                     {
                        "type": "array",
                        "minItems": 3,
                        "maxItems": 3,
                        "items": [
                           {
                              "type": "integer"
                           },
                           {
                              "type": "integer"
                           },
                           {
                              "type": "integer"
                           }
                        ]
                     }
                  ]
               }
            },
            "img_channels": {
               "title": "Img Channels",
               "description": "The number of channels of the training images.",
               "exclusiveMinimum": 0,
               "type": "integer"
            },
            "img_sz": {
               "title": "Img Sz",
               "description": "Length of a side of each image in pixels. This is the size to transform it to during training, not the size in the raw dataset.",
               "default": 256,
               "exclusiveMinimum": 0,
               "type": "integer"
            },
            "train_sz": {
               "title": "Train Sz",
               "description": "If set, the number of training images to use. If fewer images exist, then an exception will be raised.",
               "type": "integer"
            },
            "train_sz_rel": {
               "title": "Train Sz Rel",
               "description": "If set, the proportion of training images to use.",
               "type": "number"
            },
            "num_workers": {
               "title": "Num Workers",
               "description": "Number of workers to use when DataLoader makes batches.",
               "default": 4,
               "type": "integer"
            },
            "augmentors": {
               "title": "Augmentors",
               "description": "Names of albumentations augmentors to use for training batches. Choices include: ['Blur', 'RandomRotate90', 'HorizontalFlip', 'VerticalFlip', 'GaussianBlur', 'GaussNoise', 'RGBShift', 'ToGray']. Alternatively, a custom transform can be provided via the aug_transform option.",
               "default": [
                  "RandomRotate90",
                  "HorizontalFlip",
                  "VerticalFlip"
               ],
               "type": "array",
               "items": {
                  "type": "string"
               }
            },
            "base_transform": {
               "title": "Base Transform",
               "description": "An Albumentations transform serialized as a dict that will be applied to all datasets: training, validation, and test. This transformation is in addition to the resizing due to img_sz. This is useful for, for example, applying the same normalization to all datasets.",
               "type": "object"
            },
            "aug_transform": {
               "title": "Aug Transform",
               "description": "An Albumentations transform serialized as a dict that will be applied as data augmentation to the training dataset. This transform is applied before base_transform. If provided, the augmentors option is ignored.",
               "type": "object"
            },
            "plot_options": {
               "title": "Plot Options",
               "description": "Options to control plotting.",
               "default": {
                  "transform": {
                     "__version__": "1.4.1",
                     "transform": {
                        "__class_fullname__": "rastervision.pytorch_learner.utils.utils.MinMaxNormalize",
                        "always_apply": false,
                        "p": 1.0,
                        "min_val": 0.0,
                        "max_val": 1.0,
                        "dtype": 5
                     }
                  },
                  "channel_display_groups": null,
                  "type_hint": "plot_options"
               },
               "allOf": [
                  {
                     "$ref": "#/definitions/PlotOptions"
                  }
               ]
            },
            "preview_batch_limit": {
               "title": "Preview Batch Limit",
               "description": "Optional limit on the number of items in the preview plots produced during training.",
               "type": "integer"
            },
            "type_hint": {
               "title": "Type Hint",
               "default": "data",
               "enum": [
                  "data"
               ],
               "type": "string"
            }
         },
         "additionalProperties": false
      }
   }
}

Config
  • extra: str = forbid

  • validate_assignment: bool = True

Fields
Validators
  • validate_class_loss_weights » all fields

  • validate_run_tensorboard » run_tensorboard

field data: DataConfig [Required]#
Validated by
  • validate_class_loss_weights

field eval_train: bool = False#

If True, runs final evaluation on training set (in addition to validation set). Useful for debugging.

Validated by
  • validate_class_loss_weights

field log_tensorboard: bool = True#

Save Tensorboard log files at the end of each epoch.

Validated by
  • validate_class_loss_weights

field model: Optional[RegressionModelConfig] = None#
Validated by
  • validate_class_loss_weights

field output_uri: Optional[str] = None#

URI of where to save output

Validated by
  • validate_class_loss_weights

field run_tensorboard: bool = False#

run Tensorboard server during training

Validated by
  • validate_class_loss_weights

  • validate_run_tensorboard

field save_all_checkpoints: bool = False#

If True, all checkpoints would be saved. The latest checkpoint would be saved as last-model.pth. The checkpoints prior to last epoch are stored as model-ckpt-epoch-{N}.pth where N is the epoch number.

Validated by
  • validate_class_loss_weights

field save_model_bundle: bool = True#

If True, saves a model bundle at the end of training which is zip file with model and this LearnerConfig which can be used to make predictions on new images at a later time.

Validated by
  • validate_class_loss_weights

field solver: Optional[SolverConfig] = None#
Validated by
  • validate_class_loss_weights

field type_hint: Literal['regression_learner'] = 'regression_learner'#
Validated by
  • validate_class_loss_weights

build(tmp_dir, model_weights_path=None, model_def_path=None, loss_def_path=None, training=True)[source]#

Returns a Learner instantiated using this Config.

Parameters
  • tmp_dir (str) – Root of temp dirs.

  • model_weights_path (str, optional) – A local path to model weights. Defaults to None.

  • model_def_path (str, optional) – A local path to a directory with a hubconf.py. If provided, the model definition is imported from here. Defaults to None.

  • loss_def_path (str, optional) – A local path to a directory with a hubconf.py. If provided, the loss function definition is imported from here. Defaults to None.

  • training (bool, optional) – Whether the model is to be used for training or prediction. If False, the model is put in eval mode and the loss function, optimizer, etc. are not initialized. Defaults to True.

classmethod from_file(uri: str) Config#

Deserialize a Config from a JSON file, upgrading if possible.

Parameters

uri (str) – URI to load from.

Return type

Config

get_model_bundle_uri() str#

Returns the URI of where the model bundle is stored.

Return type

str

recursive_validate_config()#

Recursively validate hierarchies of Configs.

This uses reflection to call validate_config on a hierarchy of Configs using a depth-first pre-order traversal.

revalidate()#

Re-validate an instantiated Config.

Runs all Pydantic validators plus self.validate_config().

Adapted from: https://github.com/samuelcolvin/pydantic/issues/1864#issuecomment-679044432

to_file(uri: str, with_rv_metadata: bool = True) None#

Save a Config to a JSON file, optionally with RV metadata.

Parameters
  • uri (str) – URI to save to.

  • with_rv_metadata (bool) – If True, inject Raster Vision metadata such as plugin_versions, so that the config can be upgraded when loaded.

Return type

None

update(*args, **kwargs)#

Update any fields before validation.

Subclasses should override this to provide complex default behavior, for example, setting default values as a function of the values of other fields. The arguments to this method will vary depending on the type of Config.

validator validate_class_loss_weights  »  all fields#
Parameters

values (dict) –

Return type

dict

validate_config()#

Validate fields that should be checked after update is called.

This is to complement the builtin validation that Pydantic performs at the time of object construction.

validate_list(field: str, valid_options: List[str])#

Validate a list field.

Parameters
  • field (str) – name of field to validate

  • valid_options (List[str]) – values that field is allowed to take

Raises

ConfigError – if field is invalid

validator validate_run_tensorboard  »  run_tensorboard#
Parameters
Return type

bool