cli
darts.cli
¶
Entrypoint for the darts-pipeline CLI.
LoggingManager
module-attribute
¶
LoggingManager = (
darts.utils.logging.LoggingManagerSingleton()
)
app
module-attribute
¶
app = cyclopts.App(
version=darts.__version__,
console=rich.get_console(),
config=darts.cli.config_parser,
help_format="plaintext",
version_format="plaintext",
)
pipeline_group
module-attribute
¶
AOISentinel2Pipeline
dataclass
¶
AOISentinel2Pipeline(
model_files: list[pathlib.Path] = None,
output_data_dir: pathlib.Path = pathlib.Path(
"data/output"
),
arcticdem_dir: pathlib.Path = pathlib.Path(
"data/download/arcticdem"
),
tcvis_dir: pathlib.Path = pathlib.Path(
"data/download/tcvis"
),
device: typing.Literal["cuda", "cpu", "auto"]
| int
| None = None,
ee_project: str | None = None,
ee_use_highvolume: bool = True,
tpi_outer_radius: int = 100,
tpi_inner_radius: int = 0,
patch_size: int = 1024,
overlap: int = 256,
batch_size: int = 8,
reflection: int = 0,
binarization_threshold: float = 0.5,
mask_erosion_size: int = 10,
min_object_size: int = 32,
quality_level: int
| typing.Literal[
"high_quality", "low_quality", "none"
] = 1,
export_bands: list[str] = lambda: [
"probabilities",
"binarized",
"polygonized",
"extent",
"thumbnail",
](),
write_model_outputs: bool = False,
overwrite: bool = False,
aoi_shapefile: pathlib.Path = None,
start_date: str = None,
end_date: str = None,
max_cloud_cover: int = 10,
input_cache: pathlib.Path = pathlib.Path(
"data/cache/input"
),
)
Bases: darts.pipelines.sequential_v2._BasePipeline
Pipeline for Sentinel 2 data based on an area of interest.
Parameters:
-
aoi_shapefile
(pathlib.Path
, default:None
) –The shapefile containing the area of interest.
-
start_date
(str
, default:None
) –The start date of the time series in YYYY-MM-DD format.
-
end_date
(str
, default:None
) –The end date of the time series in YYYY-MM-DD format.
-
max_cloud_cover
(int
, default:10
) –The maximum cloud cover percentage to use for filtering the Sentinel 2 scenes. Defaults to 10.
-
input_cache
(pathlib.Path
, default:pathlib.Path('data/cache/input')
) –The directory to use for caching the input data. Defaults to Path("data/cache/input").
-
model_files
(pathlib.Path | list[pathlib.Path]
, default:None
) –The path to the models to use for segmentation. Can also be a single Path to only use one model. This implies
write_model_outputs=False
If a list is provided, will use an ensemble of the models. -
output_data_dir
(pathlib.Path
, default:pathlib.Path('data/output')
) –The "output" directory. Defaults to Path("data/output").
-
arcticdem_dir
(pathlib.Path
, default:pathlib.Path('data/download/arcticdem')
) –The directory containing the ArcticDEM data (the datacube and the extent files). Will be created and downloaded if it does not exist. Defaults to Path("data/download/arcticdem").
-
tcvis_dir
(pathlib.Path
, default:pathlib.Path('data/download/tcvis')
) –The directory containing the TCVis data. Defaults to Path("data/download/tcvis").
-
device
(typing.Literal['cuda', 'cpu'] | int
, default:None
) –The device to run the model on. If "cuda" take the first device (0), if int take the specified device. If "auto" try to automatically select a free GPU (<50% memory usage). Defaults to "cuda" if available, else "cpu".
-
ee_project
(str
, default:None
) –The Earth Engine project ID or number to use. May be omitted if project is defined within persistent API credentials obtained via
earthengine authenticate
. -
ee_use_highvolume
(bool
, default:True
) –Whether to use the high volume server (https://earthengine-highvolume.googleapis.com).
-
tpi_outer_radius
(int
, default:100
) –The outer radius of the annulus kernel for the tpi calculation in m. Defaults to 100m.
-
tpi_inner_radius
(int
, default:0
) –The inner radius of the annulus kernel for the tpi calculation in m. Defaults to 0.
-
patch_size
(int
, default:1024
) –The patch size to use for inference. Defaults to 1024.
-
overlap
(int
, default:256
) –The overlap to use for inference. Defaults to 16.
-
batch_size
(int
, default:8
) –The batch size to use for inference. Defaults to 8.
-
reflection
(int
, default:0
) –The reflection padding to use for inference. Defaults to 0.
-
binarization_threshold
(float
, default:0.5
) –The threshold to binarize the probabilities. Defaults to 0.5.
-
mask_erosion_size
(int
, default:10
) –The size of the disk to use for mask erosion and the edge-cropping. Defaults to 10.
-
min_object_size
(int
, default:32
) –The minimum object size to keep in pixel. Defaults to 32.
-
quality_level
(int | typing.Literal['high_quality', 'low_quality', 'none']
, default:1
) –The quality level to use for the segmentation. Can also be an int. In this case 0="none" 1="low_quality" 2="high_quality". Defaults to 1.
-
export_bands
(list[str]
, default:lambda: ['probabilities', 'binarized', 'polygonized', 'extent', 'thumbnail']()
) –The bands to export. Can be a list of "probabilities", "binarized", "polygonized", "extent", "thumbnail", "optical", "dem", "tcvis" or concrete band-names. Defaults to ["probabilities", "binarized", "polygonized", "extent", "thumbnail"].
-
write_model_outputs
(bool
, default:False
) –Also save the model outputs, not only the ensemble result. Defaults to False.
-
overwrite
(bool
, default:False
) –Whether to overwrite existing files. Defaults to False.
arcticdem_dir
class-attribute
instance-attribute
¶
device
class-attribute
instance-attribute
¶
export_bands
class-attribute
instance-attribute
¶
export_bands: list[str] = dataclasses.field(
default_factory=lambda: [
"probabilities",
"binarized",
"polygonized",
"extent",
"thumbnail",
]
)
input_cache
class-attribute
instance-attribute
¶
output_data_dir
class-attribute
instance-attribute
¶
quality_level
class-attribute
instance-attribute
¶
tcvis_dir
class-attribute
instance-attribute
¶
cli
staticmethod
¶
cli(
*,
pipeline: darts.pipelines.sequential_v2.AOISentinel2Pipeline,
)
run
¶
Source code in darts/src/darts/pipelines/sequential_v2.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
|
ConfigParser
¶
Parser for cyclopts config.
An own implementation is needed to select our own toml structure and source. Implemented as a class to be able to provide the config-file as a parameter of the CLI.
Initialize the ConfigParser (no-op).
Source code in darts/src/darts/utils/config.py
__call__
¶
__call__(
apps: list[cyclopts.App],
commands: tuple[str, ...],
arguments: cyclopts.ArgumentCollection,
)
Parser for cyclopts config. An own implementation is needed to select our own toml structure.
First, the configuration file at "config.toml" is loaded. Then, this config is flattened and then mapped to the input arguments of the called function. Hence parent keys are not considered.
Parameters:
-
apps
(list[cyclopts.App]
) –The cyclopts apps. Unused, but must be provided for the cyclopts hook.
-
commands
(tuple[str, ...]
) –The commands. Unused, but must be provided for the cyclopts hook.
-
arguments
(cyclopts.ArgumentCollection
) –The arguments to apply the config to.
Examples:
Setup the cyclopts App¶
import cyclopts
from darts.utils.config import ConfigParser
config_parser = ConfigParser()
app = cyclopts.App(config=config_parser)
# Intercept the logging behavior to add a file handler
@app.meta.default
def launcher(
*tokens: Annotated[str, cyclopts.Parameter(show=False, allow_leading_hyphen=True)],
log_dir: Path = Path("logs"),
config_file: Path = Path("config.toml"),
):
command, bound, _ = app.parse_args(tokens)
add_logging_handlers(command.__name__, console, log_dir)
return command(*bound.args, **bound.kwargs)
if __name__ == "__main__":
app.meta()
Usage¶
Config file ./config.toml
:
Function signature which is called:
Calling the function from CLI:
Source code in darts/src/darts/utils/config.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
apply_config
¶
Apply the loaded config to the cyclopts mapping.
Parameters:
-
arguments
(cyclopts.ArgumentCollection
) –The arguments to apply the config to.
Source code in darts/src/darts/utils/config.py
open_config
¶
Open the config file, takes the 'darts' key, flattens the resulting dict and saves as config.
Parameters:
Source code in darts/src/darts/utils/config.py
PlanetPipeline
dataclass
¶
PlanetPipeline(
model_files: list[pathlib.Path] = None,
output_data_dir: pathlib.Path = pathlib.Path(
"data/output"
),
arcticdem_dir: pathlib.Path = pathlib.Path(
"data/download/arcticdem"
),
tcvis_dir: pathlib.Path = pathlib.Path(
"data/download/tcvis"
),
device: typing.Literal["cuda", "cpu", "auto"]
| int
| None = None,
ee_project: str | None = None,
ee_use_highvolume: bool = True,
tpi_outer_radius: int = 100,
tpi_inner_radius: int = 0,
patch_size: int = 1024,
overlap: int = 256,
batch_size: int = 8,
reflection: int = 0,
binarization_threshold: float = 0.5,
mask_erosion_size: int = 10,
min_object_size: int = 32,
quality_level: int
| typing.Literal[
"high_quality", "low_quality", "none"
] = 1,
export_bands: list[str] = lambda: [
"probabilities",
"binarized",
"polygonized",
"extent",
"thumbnail",
](),
write_model_outputs: bool = False,
overwrite: bool = False,
orthotiles_dir: pathlib.Path = pathlib.Path(
"data/input/planet/PSOrthoTile"
),
scenes_dir: pathlib.Path = pathlib.Path(
"data/input/planet/PSScene"
),
image_ids: list = None,
)
Bases: darts.pipelines.sequential_v2._BasePipeline
Pipeline for PlanetScope data.
Parameters:
-
orthotiles_dir
(pathlib.Path
, default:pathlib.Path('data/input/planet/PSOrthoTile')
) –The directory containing the PlanetScope orthotiles.
-
scenes_dir
(pathlib.Path
, default:pathlib.Path('data/input/planet/PSScene')
) –The directory containing the PlanetScope scenes.
-
image_ids
(list
, default:None
) –The list of image ids to process. If None, all images in the directory will be processed.
-
model_files
(pathlib.Path | list[pathlib.Path]
, default:None
) –The path to the models to use for segmentation. Can also be a single Path to only use one model. This implies
write_model_outputs=False
If a list is provided, will use an ensemble of the models. -
output_data_dir
(pathlib.Path
, default:pathlib.Path('data/output')
) –The "output" directory. Defaults to Path("data/output").
-
arcticdem_dir
(pathlib.Path
, default:pathlib.Path('data/download/arcticdem')
) –The directory containing the ArcticDEM data (the datacube and the extent files). Will be created and downloaded if it does not exist. Defaults to Path("data/download/arcticdem").
-
tcvis_dir
(pathlib.Path
, default:pathlib.Path('data/download/tcvis')
) –The directory containing the TCVis data. Defaults to Path("data/download/tcvis").
-
device
(typing.Literal['cuda', 'cpu'] | int
, default:None
) –The device to run the model on. If "cuda" take the first device (0), if int take the specified device. If "auto" try to automatically select a free GPU (<50% memory usage). Defaults to "cuda" if available, else "cpu".
-
ee_project
(str
, default:None
) –The Earth Engine project ID or number to use. May be omitted if project is defined within persistent API credentials obtained via
earthengine authenticate
. -
ee_use_highvolume
(bool
, default:True
) –Whether to use the high volume server (https://earthengine-highvolume.googleapis.com).
-
tpi_outer_radius
(int
, default:100
) –The outer radius of the annulus kernel for the tpi calculation in m. Defaults to 100m.
-
tpi_inner_radius
(int
, default:0
) –The inner radius of the annulus kernel for the tpi calculation in m. Defaults to 0.
-
patch_size
(int
, default:1024
) –The patch size to use for inference. Defaults to 1024.
-
overlap
(int
, default:256
) –The overlap to use for inference. Defaults to 16.
-
batch_size
(int
, default:8
) –The batch size to use for inference. Defaults to 8.
-
reflection
(int
, default:0
) –The reflection padding to use for inference. Defaults to 0.
-
binarization_threshold
(float
, default:0.5
) –The threshold to binarize the probabilities. Defaults to 0.5.
-
mask_erosion_size
(int
, default:10
) –The size of the disk to use for mask erosion and the edge-cropping. Defaults to 10.
-
min_object_size
(int
, default:32
) –The minimum object size to keep in pixel. Defaults to 32.
-
quality_level
(int | typing.Literal['high_quality', 'low_quality', 'none']
, default:1
) –The quality level to use for the segmentation. Can also be an int. In this case 0="none" 1="low_quality" 2="high_quality". Defaults to 1.
-
export_bands
(list[str]
, default:lambda: ['probabilities', 'binarized', 'polygonized', 'extent', 'thumbnail']()
) –The bands to export. Can be a list of "probabilities", "binarized", "polygonized", "extent", "thumbnail", "optical", "dem", "tcvis" or concrete band-names. Defaults to ["probabilities", "binarized", "polygonized", "extent", "thumbnail"].
-
write_model_outputs
(bool
, default:False
) –Also save the model outputs, not only the ensemble result. Defaults to False.
-
overwrite
(bool
, default:False
) –Whether to overwrite existing files. Defaults to False.
arcticdem_dir
class-attribute
instance-attribute
¶
device
class-attribute
instance-attribute
¶
export_bands
class-attribute
instance-attribute
¶
export_bands: list[str] = dataclasses.field(
default_factory=lambda: [
"probabilities",
"binarized",
"polygonized",
"extent",
"thumbnail",
]
)
orthotiles_dir
class-attribute
instance-attribute
¶
output_data_dir
class-attribute
instance-attribute
¶
quality_level
class-attribute
instance-attribute
¶
scenes_dir
class-attribute
instance-attribute
¶
tcvis_dir
class-attribute
instance-attribute
¶
cli
staticmethod
¶
cli(
*,
pipeline: darts.pipelines.sequential_v2.PlanetPipeline,
)
run
¶
Source code in darts/src/darts/pipelines/sequential_v2.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
|
Sentinel2Pipeline
dataclass
¶
Sentinel2Pipeline(
model_files: list[pathlib.Path] = None,
output_data_dir: pathlib.Path = pathlib.Path(
"data/output"
),
arcticdem_dir: pathlib.Path = pathlib.Path(
"data/download/arcticdem"
),
tcvis_dir: pathlib.Path = pathlib.Path(
"data/download/tcvis"
),
device: typing.Literal["cuda", "cpu", "auto"]
| int
| None = None,
ee_project: str | None = None,
ee_use_highvolume: bool = True,
tpi_outer_radius: int = 100,
tpi_inner_radius: int = 0,
patch_size: int = 1024,
overlap: int = 256,
batch_size: int = 8,
reflection: int = 0,
binarization_threshold: float = 0.5,
mask_erosion_size: int = 10,
min_object_size: int = 32,
quality_level: int
| typing.Literal[
"high_quality", "low_quality", "none"
] = 1,
export_bands: list[str] = lambda: [
"probabilities",
"binarized",
"polygonized",
"extent",
"thumbnail",
](),
write_model_outputs: bool = False,
overwrite: bool = False,
sentinel2_dir: pathlib.Path = pathlib.Path(
"data/input/sentinel2"
),
image_ids: list = None,
)
Bases: darts.pipelines.sequential_v2._BasePipeline
Pipeline for Sentinel 2 data.
Parameters:
-
sentinel2_dir
(pathlib.Path
, default:pathlib.Path('data/input/sentinel2')
) –The directory containing the Sentinel 2 scenes. Defaults to Path("data/input/sentinel2").
-
image_ids
(list
, default:None
) –The list of image ids to process. If None, all images in the directory will be processed. Defaults to None.
-
model_files
(pathlib.Path | list[pathlib.Path]
, default:None
) –The path to the models to use for segmentation. Can also be a single Path to only use one model. This implies
write_model_outputs=False
If a list is provided, will use an ensemble of the models. -
output_data_dir
(pathlib.Path
, default:pathlib.Path('data/output')
) –The "output" directory. Defaults to Path("data/output").
-
arcticdem_dir
(pathlib.Path
, default:pathlib.Path('data/download/arcticdem')
) –The directory containing the ArcticDEM data (the datacube and the extent files). Will be created and downloaded if it does not exist. Defaults to Path("data/download/arcticdem").
-
tcvis_dir
(pathlib.Path
, default:pathlib.Path('data/download/tcvis')
) –The directory containing the TCVis data. Defaults to Path("data/download/tcvis").
-
device
(typing.Literal['cuda', 'cpu'] | int
, default:None
) –The device to run the model on. If "cuda" take the first device (0), if int take the specified device. If "auto" try to automatically select a free GPU (<50% memory usage). Defaults to "cuda" if available, else "cpu".
-
ee_project
(str
, default:None
) –The Earth Engine project ID or number to use. May be omitted if project is defined within persistent API credentials obtained via
earthengine authenticate
. -
ee_use_highvolume
(bool
, default:True
) –Whether to use the high volume server (https://earthengine-highvolume.googleapis.com).
-
tpi_outer_radius
(int
, default:100
) –The outer radius of the annulus kernel for the tpi calculation in m. Defaults to 100m.
-
tpi_inner_radius
(int
, default:0
) –The inner radius of the annulus kernel for the tpi calculation in m. Defaults to 0.
-
patch_size
(int
, default:1024
) –The patch size to use for inference. Defaults to 1024.
-
overlap
(int
, default:256
) –The overlap to use for inference. Defaults to 16.
-
batch_size
(int
, default:8
) –The batch size to use for inference. Defaults to 8.
-
reflection
(int
, default:0
) –The reflection padding to use for inference. Defaults to 0.
-
binarization_threshold
(float
, default:0.5
) –The threshold to binarize the probabilities. Defaults to 0.5.
-
mask_erosion_size
(int
, default:10
) –The size of the disk to use for mask erosion and the edge-cropping. Defaults to 10.
-
min_object_size
(int
, default:32
) –The minimum object size to keep in pixel. Defaults to 32.
-
quality_level
(int | typing.Literal['high_quality', 'low_quality', 'none']
, default:1
) –The quality level to use for the segmentation. Can also be an int. In this case 0="none" 1="low_quality" 2="high_quality". Defaults to 1.
-
export_bands
(list[str]
, default:lambda: ['probabilities', 'binarized', 'polygonized', 'extent', 'thumbnail']()
) –The bands to export. Can be a list of "probabilities", "binarized", "polygonized", "extent", "thumbnail", "optical", "dem", "tcvis" or concrete band-names. Defaults to ["probabilities", "binarized", "polygonized", "extent", "thumbnail"].
-
write_model_outputs
(bool
, default:False
) –Also save the model outputs, not only the ensemble result. Defaults to False.
-
overwrite
(bool
, default:False
) –Whether to overwrite existing files. Defaults to False.
arcticdem_dir
class-attribute
instance-attribute
¶
device
class-attribute
instance-attribute
¶
export_bands
class-attribute
instance-attribute
¶
export_bands: list[str] = dataclasses.field(
default_factory=lambda: [
"probabilities",
"binarized",
"polygonized",
"extent",
"thumbnail",
]
)
output_data_dir
class-attribute
instance-attribute
¶
quality_level
class-attribute
instance-attribute
¶
sentinel2_dir
class-attribute
instance-attribute
¶
tcvis_dir
class-attribute
instance-attribute
¶
cli
staticmethod
¶
cli(
*,
pipeline: darts.pipelines.sequential_v2.Sentinel2Pipeline,
)
run
¶
Source code in darts/src/darts/pipelines/sequential_v2.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
|
benchviz
¶
Visulize benchmark based on a Stopuhr data file produced by a pipeline run.
Note
This function changes the seaborn theme to "whitegrid" for better visualization.
Parameters:
-
stopuhr_data
(pathlib.Path
) –Path to the Stopuhr data file.
-
viz_dir
(pathlib.Path | None
, default:None
) –Path to the directory where the visualization will be saved. If None, the defaults to the parent directory of the Stopuhr data file. Defaults to None.
Returns:
-
–
plt.Figure: A matplotlib figure containing the benchmark visualization.
Source code in darts/src/darts/utils/bench.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
|
convert_lightning_checkpoint
¶
convert_lightning_checkpoint(
*,
lightning_checkpoint: pathlib.Path,
out_directory: pathlib.Path,
checkpoint_name: str,
framework: str = "smp",
)
Convert a lightning checkpoint to our own format.
The final checkpoint will contain the model configuration and the state dict. It will be saved to:
Parameters:
-
lightning_checkpoint
(pathlib.Path
) –Path to the lightning checkpoint.
-
out_directory
(pathlib.Path
) –Output directory for the converted checkpoint.
-
checkpoint_name
(str
) –A unique name of the new checkpoint.
-
framework
(str
, default:'smp'
) –The framework used for the model. Defaults to "smp".
Source code in darts-segmentation/src/darts_segmentation/training/train.py
cross_validation_smp
¶
cross_validation_smp(
*,
name: str | None = None,
tune_name: str | None = None,
cv: darts_segmentation.training.cv.CrossValidationConfig = darts_segmentation.training.cv.CrossValidationConfig(),
training_config: darts_segmentation.training.train.TrainingConfig = darts_segmentation.training.train.TrainingConfig(),
data_config: darts_segmentation.training.train.DataConfig = darts_segmentation.training.train.DataConfig(),
device_config: darts_segmentation.training.train.DeviceConfig = darts_segmentation.training.train.DeviceConfig(),
hparams: darts_segmentation.training.hparams.Hyperparameters = darts_segmentation.training.hparams.Hyperparameters(),
logging_config: darts_segmentation.training.train.LoggingConfig = darts_segmentation.training.train.LoggingConfig(),
)
Perform cross-validation for a model with given hyperparameters.
Please see https://smp.readthedocs.io/en/latest/index.html for model configurations of architecture and encoder.
Please also consider reading our training guide (docs/guides/training.md).
This cross-validation function is designed to evaluate the performance of a single model configuration. It can be used by a tuning script to tune hyperparameters. It calls the training function, hence most functionality is the same as the training function. In general, it does perform this:
and calculates a score from the results.
To specify on which metric(s) the score is calculated, the scoring_metric
parameter can be specified.
Each score can be provided by either ":higher" or ":lower" to indicate the direction of the metrics.
This allows to correctly combine multiple metrics by doing 1/metric before calculation if a metric is ":lower".
If no direction is provided, it is assumed to be ":higher".
Has no real effect on the single score calculation, since only the mean is calculated there.
In a multi-score setting, the score is calculated by combine-then-reduce the metrics. Meaning that first for each fold the metrics are combined using the specified strategy, and then the results are reduced via mean. Please refer to the documentation to understand the different multi-score strategies.
If one of the metrics of any of the runs contains NaN, Inf, -Inf or is 0 the score is reported to be "unstable".
Artifacts are stored under {artifact_dir}/{tune_name}
for tunes (meaning if tune_name
is not None)
else {artifact_dir}/_cross_validation
.
You can specify the frequency on how often logs will be written and validation will be performed.
- log_every_n_steps
specifies how often train-logs will be written. This does not affect validation.
- check_val_every_n_epoch
specifies how often validation will be performed.
This will also affect early stopping.
- early_stopping_patience
specifies how many epochs to wait for improvement before stopping.
In epochs, this would be check_val_every_n_epoch * early_stopping_patience
.
- plot_every_n_val_epochs
specifies how often validation samples will be plotted.
Since plotting is quite costly, you can reduce the frequency. Works similar like early stopping.
In epochs, this would be check_val_every_n_epoch * plot_every_n_val_epochs
.
Example: There are 400 training samples and the batch size is 2, resulting in 200 training steps per epoch.
If log_every_n_steps
is set to 50 then the training logs and metrics will be logged 4 times per epoch.
If check_val_every_n_epoch
is set to 5 then validation will be performed every 5 epochs.
If plot_every_n_val_epochs
is set to 2 then validation samples will be plotted every 10 epochs.
If early_stopping_patience
is set to 3 then early stopping will be performed after 15 epochs without improvement.
The data structure of the training data expects the "preprocessing" step to be done beforehand, which results in the following data structure:
preprocessed-data/ # the top-level directory
├── config.toml
├── data.zarr/ # this zarr group contains the dataarrays x and y
├── metadata.parquet # this contains information necessary to split the data into train, val, and test sets.
└── labels.geojson
Parameters:
-
name
(str | None
, default:None
) –Name of the cross-validation. If None, a name is generated automatically. Defaults to None.
-
tune_name
(str | None
, default:None
) –Name of the tuning. Should only be specified by a tuning script. Defaults to None.
-
cv
(darts_segmentation.training.cv.CrossValidationConfig
, default:darts_segmentation.training.cv.CrossValidationConfig()
) –Configuration for cross-validation.
-
training_config
(darts_segmentation.training.train.TrainingConfig
, default:darts_segmentation.training.train.TrainingConfig()
) –Configuration for the training.
-
data_config
(darts_segmentation.training.train.DataConfig
, default:darts_segmentation.training.train.DataConfig()
) –Configuration for the data.
-
device_config
(darts_segmentation.training.train.DeviceConfig
, default:darts_segmentation.training.train.DeviceConfig()
) –Configuration for the devices to use.
-
hparams
(darts_segmentation.training.hparams.Hyperparameters
, default:darts_segmentation.training.hparams.Hyperparameters()
) –Hyperparameters for the training.
-
logging_config
(darts_segmentation.training.train.LoggingConfig
, default:darts_segmentation.training.train.LoggingConfig()
) –Logging configuration.
Returns:
-
–
tuple[float, bool, pd.DataFrame]: A single score, a boolean indicating if the score is unstable, and a DataFrame containing run info (seed, fold, metrics, duration, checkpoint)
Raises:
-
ValueError
–If no runs were performed, meaning the configuration is invalid or no data was found.
Source code in darts-segmentation/src/darts_segmentation/training/cv.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
|
env_info
¶
hello
¶
Say hello to someone.
Parameters:
-
name
(str
) –The name of the person to say hello to
-
n
(int
, default:1
) –The number of times to say hello. Defaults to 1.
Raises:
-
ValueError
–If n is 3.
Source code in darts/src/darts/cli.py
help
¶
launcher
¶
launcher(
*tokens: str,
log_dir: pathlib.Path = pathlib.Path("logs"),
config_file: pathlib.Path = pathlib.Path("config.toml"),
verbose: bool = False,
tracebacks_show_locals: bool = False,
)
Source code in darts/src/darts/cli.py
preprocess_planet_train_data
¶
preprocess_planet_train_data(
*,
data_dir: pathlib.Path,
labels_dir: pathlib.Path,
train_data_dir: pathlib.Path,
arcticdem_dir: pathlib.Path,
tcvis_dir: pathlib.Path,
admin_dir: pathlib.Path,
preprocess_cache: pathlib.Path | None = None,
force_preprocess: bool = False,
append: bool = True,
device: typing.Literal["cuda", "cpu", "auto"]
| int
| None = None,
ee_project: str | None = None,
ee_use_highvolume: bool = True,
tpi_outer_radius: int = 100,
tpi_inner_radius: int = 0,
patch_size: int = 1024,
overlap: int = 16,
exclude_nopositive: bool = False,
exclude_nan: bool = True,
mask_erosion_size: int = 3,
)
Preprocess Planet data for training.
The data is split into a cross-validation, a validation-test and a test set:
- `cross-val` is meant to be used for train and validation
- `val-test` (5%) random leave-out for testing the randomness distribution shift of the data
- `test` leave-out region for testing the spatial distribution shift of the data
Each split is stored as a zarr group, containing a x and a y dataarray. The x dataarray contains the input data with the shape (n_patches, n_bands, patch_size, patch_size). The y dataarray contains the labels with the shape (n_patches, patch_size, patch_size). Both dataarrays are chunked along the n_patches dimension. This results in super fast random access to the data, because each sample / patch is stored in a separate chunk and therefore in a separate file.
Through the parameters test_val_split
and test_regions
, the test and validation split can be controlled.
To test_regions
can a list of admin 1 or admin 2 region names, based on the region shapefile maintained by
https://github.com/wmgeolab/geoBoundaries, be supplied to remove intersecting scenes from the dataset and
put them in the test-split.
With the test_val_split
parameter, the ratio between further splitting of a test-validation set can be controlled.
Through exclude_nopositve
and exclude_nan
, respective patches can be excluded from the final data.
Further, a config.toml
file is saved in the train_data_dir
containing the configuration used for the
preprocessing.
Addionally, a labels.geojson
file is saved in the train_data_dir
containing the joined labels geometries used
for the creation of the binarized label-masks, containing also information about the split via the mode
column.
The final directory structure of train_data_dir
will look like this:
train_data_dir/
├── config.toml
├── cross-val.zarr/
├── test.zarr/
├── val-test.zarr/
└── labels.geojson
Parameters:
-
data_dir
(pathlib.Path
) –The directory containing the Planet scenes and orthotiles.
-
labels_dir
(pathlib.Path
) –The directory containing the labels and footprints / extents.
-
train_data_dir
(pathlib.Path
) –The "output" directory where the tensors are written to.
-
arcticdem_dir
(pathlib.Path
) –The directory containing the ArcticDEM data (the datacube and the extent files). Will be created and downloaded if it does not exist.
-
tcvis_dir
(pathlib.Path
) –The directory containing the TCVis data.
-
admin_dir
(pathlib.Path
) –The directory containing the admin files.
-
preprocess_cache
(pathlib.Path
, default:None
) –The directory to store the preprocessed data. Defaults to None.
-
force_preprocess
(bool
, default:False
) –Whether to force the preprocessing of the data. Defaults to False.
-
append
(bool
, default:True
) –Whether to append the data to the existing data. Defaults to True.
-
device
(typing.Literal['cuda', 'cpu'] | int
, default:None
) –The device to run the model on. If "cuda" take the first device (0), if int take the specified device. If "auto" try to automatically select a free GPU (<50% memory usage). Defaults to "cuda" if available, else "cpu".
-
ee_project
(str
, default:None
) –The Earth Engine project ID or number to use. May be omitted if project is defined within persistent API credentials obtained via
earthengine authenticate
. -
ee_use_highvolume
(bool
, default:True
) –Whether to use the high volume server (https://earthengine-highvolume.googleapis.com).
-
tpi_outer_radius
(int
, default:100
) –The outer radius of the annulus kernel for the tpi calculation in m. Defaults to 100m.
-
tpi_inner_radius
(int
, default:0
) –The inner radius of the annulus kernel for the tpi calculation in m. Defaults to 0.
-
patch_size
(int
, default:1024
) –The patch size to use for inference. Defaults to 1024.
-
overlap
(int
, default:16
) –The overlap to use for inference. Defaults to 16.
-
exclude_nopositive
(bool
, default:False
) –Whether to exclude patches where the labels do not contain positives. Defaults to False.
-
exclude_nan
(bool
, default:True
) –Whether to exclude patches where the input data has nan values. Defaults to True.
-
mask_erosion_size
(int
, default:3
) –The size of the disk to use for mask erosion and the edge-cropping. Defaults to 10.
Source code in darts/src/darts/training/preprocess_planet_v2.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
preprocess_planet_train_data_pingo
¶
preprocess_planet_train_data_pingo(
*,
data_dir: pathlib.Path,
labels_dir: pathlib.Path,
train_data_dir: pathlib.Path,
arcticdem_dir: pathlib.Path,
tcvis_dir: pathlib.Path,
admin_dir: pathlib.Path,
preprocess_cache: pathlib.Path | None = None,
force_preprocess: bool = False,
device: typing.Literal["cuda", "cpu", "auto"]
| int
| None = None,
ee_project: str | None = None,
ee_use_highvolume: bool = True,
tpi_outer_radius: int = 100,
tpi_inner_radius: int = 0,
patch_size: int = 1024,
overlap: int = 16,
exclude_nopositive: bool = False,
exclude_nan: bool = True,
mask_erosion_size: int = 3,
)
Preprocess Planet data for training.
The data is split into a cross-validation, a validation-test and a test set:
- `cross-val` is meant to be used for train and validation
- `val-test` (5%) random leave-out for testing the randomness distribution shift of the data
- `test` leave-out region for testing the spatial distribution shift of the data
Each split is stored as a zarr group, containing a x and a y dataarray. The x dataarray contains the input data with the shape (n_patches, n_bands, patch_size, patch_size). The y dataarray contains the labels with the shape (n_patches, patch_size, patch_size). Both dataarrays are chunked along the n_patches dimension. This results in super fast random access to the data, because each sample / patch is stored in a separate chunk and therefore in a separate file.
Through the parameters test_val_split
and test_regions
, the test and validation split can be controlled.
To test_regions
can a list of admin 1 or admin 2 region names, based on the region shapefile maintained by
https://github.com/wmgeolab/geoBoundaries, be supplied to remove intersecting scenes from the dataset and
put them in the test-split.
With the test_val_split
parameter, the ratio between further splitting of a test-validation set can be controlled.
Through exclude_nopositve
and exclude_nan
, respective patches can be excluded from the final data.
Further, a config.toml
file is saved in the train_data_dir
containing the configuration used for the
preprocessing.
Addionally, a labels.geojson
file is saved in the train_data_dir
containing the joined labels geometries used
for the creation of the binarized label-masks, containing also information about the split via the mode
column.
The final directory structure of train_data_dir
will look like this:
train_data_dir/
├── config.toml
├── cross-val.zarr/
├── test.zarr/
├── val-test.zarr/
└── labels.geojson
Parameters:
-
data_dir
(pathlib.Path
) –The directory containing the Planet scenes and orthotiles.
-
labels_dir
(pathlib.Path
) –The directory containing the labels and footprints / extents.
-
train_data_dir
(pathlib.Path
) –The "output" directory where the tensors are written to.
-
arcticdem_dir
(pathlib.Path
) –The directory containing the ArcticDEM data (the datacube and the extent files). Will be created and downloaded if it does not exist.
-
tcvis_dir
(pathlib.Path
) –The directory containing the TCVis data.
-
admin_dir
(pathlib.Path
) –The directory containing the admin files.
-
preprocess_cache
(pathlib.Path
, default:None
) –The directory to store the preprocessed data. Defaults to None.
-
force_preprocess
(bool
, default:False
) –Whether to force the preprocessing of the data. Defaults to False.
-
device
(typing.Literal['cuda', 'cpu'] | int
, default:None
) –The device to run the model on. If "cuda" take the first device (0), if int take the specified device. If "auto" try to automatically select a free GPU (<50% memory usage). Defaults to "cuda" if available, else "cpu".
-
ee_project
(str
, default:None
) –The Earth Engine project ID or number to use. May be omitted if project is defined within persistent API credentials obtained via
earthengine authenticate
. -
ee_use_highvolume
(bool
, default:True
) –Whether to use the high volume server (https://earthengine-highvolume.googleapis.com).
-
tpi_outer_radius
(int
, default:100
) –The outer radius of the annulus kernel for the tpi calculation in m. Defaults to 100m.
-
tpi_inner_radius
(int
, default:0
) –The inner radius of the annulus kernel for the tpi calculation in m. Defaults to 0.
-
patch_size
(int
, default:1024
) –The patch size to use for inference. Defaults to 1024.
-
overlap
(int
, default:16
) –The overlap to use for inference. Defaults to 16.
-
exclude_nopositive
(bool
, default:False
) –Whether to exclude patches where the labels do not contain positives. Defaults to False.
-
exclude_nan
(bool
, default:True
) –Whether to exclude patches where the input data has nan values. Defaults to True.
-
mask_erosion_size
(int
, default:3
) –The size of the disk to use for mask erosion and the edge-cropping. Defaults to 10.
Source code in darts/src/darts/training/preprocess_planet_v2_pingo.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
|
shell
¶
start_app
¶
Wrapp to start the app.
Source code in darts/src/darts/cli.py
test_smp
¶
test_smp(
*,
train_data_dir: pathlib.Path,
run_id: str,
run_name: str,
model_ckp: pathlib.Path | None = None,
batch_size: int = 8,
data_split_method: typing.Literal[
"random", "region", "sample"
]
| None = None,
data_split_by: list[str] | str | float | None = None,
bands: list[str] | None = None,
artifact_dir: pathlib.Path = pathlib.Path("artifacts"),
num_workers: int = 0,
device_config: darts_segmentation.training.train.DeviceConfig = darts_segmentation.training.train.DeviceConfig(),
wandb_entity: str | None = None,
wandb_project: str | None = None,
) -> pytorch_lightning.Trainer
Run the testing of the SMP model.
The data structure of the training data expects the "preprocessing" step to be done beforehand, which results in the following data structure:
preprocessed-data/ # the top-level directory
├── config.toml
├── data.zarr/ # this zarr group contains the dataarrays x and y
├── metadata.parquet # this contains information necessary to split the data into train, val, and test sets.
└── labels.geojson
Parameters:
-
train_data_dir
(pathlib.Path
) –The path (top-level) to the data to be used for training. Expects a directory containing: 1. a zarr group called "data.zarr" containing a "x" and "y" array 2. a geoparquet file called "metadata.parquet" containing the metadata for the data. This metadata should contain at least the following columns: - "sample_id": The id of the sample - "region": The region the sample belongs to - "empty": Whether the image is empty The index should refer to the index of the sample in the zarr data. This directory should be created by a preprocessing script.
-
run_id
(str
) –ID of the run.
-
run_name
(str
) –Name of the run.
-
model_ckp
(pathlib.Path | None
, default:None
) –Path to the model checkpoint. If None, try to find the latest checkpoint in
artifact_dir / run_name / run_id / checkpoints
. Defaults to None. -
batch_size
(int
, default:8
) –Batch size for training and validation.
-
data_split_method
(typing.Literal['random', 'region', 'sample'] | None
, default:None
) –The method to use for splitting the data into a train and a test set. "random" will split the data randomly, the seed is always 42 and the size of the test set can be specified by providing a float between 0 and 1 to data_split_by. "region" will split the data by one or multiple regions, which can be specified by providing a str or list of str to data_split_by. "sample" will split the data by sample ids, which can also be specified similar to "region". If None, no split is done and the complete dataset is used for both training and testing. The train split will further be split in the cross validation process. Defaults to None.
-
data_split_by
(list[str] | str | float | None
, default:None
) –Select by which seed/regions/samples split. Defaults to None.
-
bands
(list[str] | None
, default:None
) –List of bands to use. Defaults to None.
-
artifact_dir
(pathlib.Path
, default:pathlib.Path('artifacts')
) –Directory to save artifacts. Defaults to Path("lightning_logs").
-
num_workers
(int
, default:0
) –Number of workers for the DataLoader. Defaults to 0.
-
device_config
(darts_segmentation.training.train.DeviceConfig
, default:darts_segmentation.training.train.DeviceConfig()
) –Device and distributed strategy related parameters.
-
wandb_entity
(str | None
, default:None
) –WandB entity. Defaults to None.
-
wandb_project
(str | None
, default:None
) –WandB project. Defaults to None.
Returns:
-
Trainer
(pytorch_lightning.Trainer
) –The trainer object used for training.
Source code in darts-segmentation/src/darts_segmentation/training/train.py
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 |
|
train_smp
¶
train_smp(
*,
run: darts_segmentation.training.train.TrainRunConfig = darts_segmentation.training.train.TrainRunConfig(),
training_config: darts_segmentation.training.train.TrainingConfig = darts_segmentation.training.train.TrainingConfig(),
data_config: darts_segmentation.training.train.DataConfig = darts_segmentation.training.train.DataConfig(),
logging_config: darts_segmentation.training.train.LoggingConfig = darts_segmentation.training.train.LoggingConfig(),
device_config: darts_segmentation.training.train.DeviceConfig = darts_segmentation.training.train.DeviceConfig(),
hparams: darts_segmentation.training.hparams.Hyperparameters = darts_segmentation.training.hparams.Hyperparameters(),
)
Run the training of the SMP model, specifically binary segmentation.
Please see https://smp.readthedocs.io/en/latest/index.html for model configurations of architecture and encoder.
Please also consider reading our training guide (docs/guides/training.md).
This training function is meant for single training runs but is also used for cross-validation and hyperparameter tuning by cv.py and tune.py. This strongly affects where artifacts are stored:
- Run was created by a tune:
{artifact_dir}/{tune_name}/{cv_name}/{run_name}-{run_id}
- Run was created by a cross-validation:
{artifact_dir}/_cross_validations/{cv_name}/{run_name}-{run_id}
- Single runs:
{artifact_dir}/_runs/{run_name}-{run_id}
run_name
can be specified by the user, else it is generated automatically.
In case of cross-validation, the run name is generated automatically by the cross-validation.
run_id
is generated automatically by the training function.
Both are saved to the final checkpoint.
You can specify the frequency on how often logs will be written and validation will be performed.
- log_every_n_steps
specifies how often train-logs will be written. This does not affect validation.
- check_val_every_n_epoch
specifies how often validation will be performed.
This will also affect early stopping.
- early_stopping_patience
specifies how many epochs to wait for improvement before stopping.
In epochs, this would be check_val_every_n_epoch * early_stopping_patience
.
- plot_every_n_val_epochs
specifies how often validation samples will be plotted.
Since plotting is quite costly, you can reduce the frequency. Works similar like early stopping.
In epochs, this would be check_val_every_n_epoch * plot_every_n_val_epochs
.
Example: There are 400 training samples and the batch size is 2, resulting in 200 training steps per epoch.
If log_every_n_steps
is set to 50 then the training logs and metrics will be logged 4 times per epoch.
If check_val_every_n_epoch
is set to 5 then validation will be performed every 5 epochs.
If plot_every_n_val_epochs
is set to 2 then validation samples will be plotted every 10 epochs.
If early_stopping_patience
is set to 3 then early stopping will be performed after 15 epochs without improvement.
The data structure of the training data expects the "preprocessing" step to be done beforehand, which results in the following data structure:
preprocessed-data/ # the top-level directory
├── config.toml
├── data.zarr/ # this zarr group contains the dataarrays x and y
├── metadata.parquet # this contains information necessary to split the data into train, val, and test sets.
└── labels.geojson
Parameters:
-
data_config
(darts_segmentation.training.train.DataConfig
, default:darts_segmentation.training.train.DataConfig()
) –Data related parameters for training.
-
run
(darts_segmentation.training.train.TrainRunConfig
, default:darts_segmentation.training.train.TrainRunConfig()
) –Run related parameters for training.
-
logging_config
(darts_segmentation.training.train.LoggingConfig
, default:darts_segmentation.training.train.LoggingConfig()
) –Logging related parameters for training.
-
device_config
(darts_segmentation.training.train.DeviceConfig
, default:darts_segmentation.training.train.DeviceConfig()
) –Device and distributed strategy related parameters.
-
training_config
(darts_segmentation.training.train.TrainingConfig
, default:darts_segmentation.training.train.TrainingConfig()
) –Training related parameters for training.
-
hparams
(darts_segmentation.training.hparams.Hyperparameters
, default:darts_segmentation.training.hparams.Hyperparameters()
) –Hyperparameters for the model.
Returns:
-
–
pl.Trainer: The trainer object used for training. Contains also metrics.
Source code in darts-segmentation/src/darts_segmentation/training/train.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 |
|
tune_smp
¶
tune_smp(
*,
name: str | None = None,
n_trials: int | typing.Literal["grid"] = 100,
retrain_and_test: bool = False,
cv_config: darts_segmentation.training.cv.CrossValidationConfig = darts_segmentation.training.cv.CrossValidationConfig(),
training_config: darts_segmentation.training.train.TrainingConfig = darts_segmentation.training.train.TrainingConfig(),
data_config: darts_segmentation.training.train.DataConfig = darts_segmentation.training.train.DataConfig(),
device_config: darts_segmentation.training.train.DeviceConfig = darts_segmentation.training.train.DeviceConfig(),
logging_config: darts_segmentation.training.train.LoggingConfig = darts_segmentation.training.train.LoggingConfig(),
hpconfig: pathlib.Path | None = None,
config_file: pathlib.Path | None = None,
)
Tune the hyper-parameters of the model using cross-validation and random states.
Please see https://smp.readthedocs.io/en/latest/index.html for model configurations of architecture and encoder.
Please also consider reading our training guide (docs/guides/training.md).
This tuning script is designed to sweep over hyperparameters with a cross-validation
used to evaluate each hyperparameter configuration.
Optionally, by setting retrain_and_test
to True, the best hyperparameters are then selected based on the
cross-validation scores and a new model is trained on the entire train-split and tested on the test-split.
Hyperparameters can be configured using a hpconfig
file (YAML or Toml).
Please consult the training guide or the documentation of
darts_segmentation.training.hparams.parse_hyperparameters
to learn how such a file should be structured.
Per default, a random search is performed, where the number of samples can be specified by n_trials
.
If n_trials
is set to "grid", a grid search is performed instead.
However, this expects to be every hyperparameter to be configured as either constant value or a choice / list.
To specify on which metric(s) the cv score is calculated, the scoring_metric
parameter can be specified.
Each score can be provided by either ":higher" or ":lower" to indicate the direction of the metrics.
This allows to correctly combine multiple metrics by doing 1/metric before calculation if a metric is ":lower".
If no direction is provided, it is assumed to be ":higher".
Has no real effect on the single score calculation, since only the mean is calculated there.
In a multi-score setting, the score is calculated by combine-then-reduce the metrics. Meaning that first for each fold the metrics are combined using the specified strategy, and then the results are reduced via mean. Please refer to the documentation to understand the different multi-score strategies.
If one of the metrics of any of the runs contains NaN, Inf, -Inf or is 0 the score is reported to be "unstable". In such cases, the configuration is not considered for further evaluation.
Artifacts are stored under {artifact_dir}/{tune_name}
.
You can specify the frequency on how often logs will be written and validation will be performed.
- log_every_n_steps
specifies how often train-logs will be written. This does not affect validation.
- check_val_every_n_epoch
specifies how often validation will be performed.
This will also affect early stopping.
- early_stopping_patience
specifies how many epochs to wait for improvement before stopping.
In epochs, this would be check_val_every_n_epoch * early_stopping_patience
.
- plot_every_n_val_epochs
specifies how often validation samples will be plotted.
Since plotting is quite costly, you can reduce the frequency. Works similar like early stopping.
In epochs, this would be check_val_every_n_epoch * plot_every_n_val_epochs
.
Example: There are 400 training samples and the batch size is 2, resulting in 200 training steps per epoch.
If log_every_n_steps
is set to 50 then the training logs and metrics will be logged 4 times per epoch.
If check_val_every_n_epoch
is set to 5 then validation will be performed every 5 epochs.
If plot_every_n_val_epochs
is set to 2 then validation samples will be plotted every 10 epochs.
If early_stopping_patience
is set to 3 then early stopping will be performed after 15 epochs without improvement.
The data structure of the training data expects the "preprocessing" step to be done beforehand, which results in the following data structure:
preprocessed-data/ # the top-level directory
├── config.toml
├── data.zarr/ # this zarr group contains the dataarrays x and y
├── metadata.parquet # this contains information necessary to split the data into train, val, and test sets.
└── labels.geojson
Parameters:
-
name
(str | None
, default:None
) –Name of the tuning run. Will be generated based on the number of existing directories in the artifact directory if None. Defaults to None.
-
n_trials
(int | typing.Literal['grid']
, default:100
) –Number of trials to perform in hyperparameter tuning. If "grid", span a grid search over all configured hyperparameters. In a grid search, only constant or choice hyperparameters are allowed. Defaults to 100.
-
retrain_and_test
(bool
, default:False
) –Whether to retrain the model with the best hyperparameters and test it. Defaults to False.
-
cv_config
(darts_segmentation.training.cv.CrossValidationConfig
, default:darts_segmentation.training.cv.CrossValidationConfig()
) –Configuration for cross-validation. Defaults to CrossValidationConfig().
-
training_config
(darts_segmentation.training.train.TrainingConfig
, default:darts_segmentation.training.train.TrainingConfig()
) –Configuration for training. Defaults to TrainingConfig().
-
data_config
(darts_segmentation.training.train.DataConfig
, default:darts_segmentation.training.train.DataConfig()
) –Configuration for data. Defaults to DataConfig().
-
device_config
(darts_segmentation.training.train.DeviceConfig
, default:darts_segmentation.training.train.DeviceConfig()
) –Configuration for device. Defaults to DeviceConfig().
-
logging_config
(darts_segmentation.training.train.LoggingConfig
, default:darts_segmentation.training.train.LoggingConfig()
) –Configuration for logging. Defaults to LoggingConfig().
-
hpconfig
(pathlib.Path | None
, default:None
) –Path to the hyperparameter configuration file. Please see the documentation of
hyperparameters
for more information. Defaults to None. -
config_file
(pathlib.Path | None
, default:None
) –Path to the configuration file. If provided, it will be used instead of
hpconfig
ifhpconfig
is None. Defaults to None.
Returns:
-
–
tuple[float, pd.DataFrame]: The best score (if retrained and tested) and the run infos of all runs.
Raises:
-
ValueError
–If no hyperparameter configuration file is provided.
Source code in darts-segmentation/src/darts_segmentation/training/tune.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
|