### Setup pre-commit Source: https://deepforest.readthedocs.io/en/stable/development/contributing.html Commands to install pre-commit and its hooks in the local repository. ```bash pip install pre-commit ``` ```bash pre-commit install ``` ```bash pre-commit run --all-files ``` -------------------------------- ### Install DeepForest from Source Source: https://deepforest.readthedocs.io/en/stable/getting_started/install.html Installation commands for installing directly from the GitHub repository. ```bash pip install git+https://github.com/weecology/DeepForest.git ``` ```bash uv add "deepforest @ git+https://github.com/weecology/deepforest" ``` -------------------------------- ### Clone and Install Locally Source: https://deepforest.readthedocs.io/en/stable/getting_started/install.html Commands to clone the repository and perform a local installation. ```bash git clone https://github.com/weecology/DeepForest.git cd DeepForest pip install . ``` ```bash git clone https://github.com/weecology/DeepForest.git cd DeepForest uv sync --all-extras --dev ``` -------------------------------- ### Install dependencies Source: https://deepforest.readthedocs.io/en/stable/development/contributing.html Commands to install the package and development requirements using pip or uv. ```bash pip install .'[dev,docs]' ``` ```bash uv sync --all-extras --dev ``` -------------------------------- ### Install for Development Source: https://deepforest.readthedocs.io/en/stable/getting_started/install.html Commands to install the package in editable mode with development and documentation dependencies. ```bash git clone https://github.com/weecology/DeepForest.git cd DeepForest pip install .'[dev,docs]' ``` ```bash git clone https://github.com/weecology/DeepForest.git cd DeepForest uv sync --all-extras --dev ``` -------------------------------- ### Setup Metrics Source: https://deepforest.readthedocs.io/en/stable/source/deepforest.html Initializes the metrics for evaluation during training and validation. ```APIDOC ## setup_metrics ### Description Initializes metrics for evaluation. ``` -------------------------------- ### Clone and install DeepForest locally using uv Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/install.md.txt Clone the DeepForest repository and install it locally using uv. ```bash git clone https://github.com/weecology/DeepForest.git cd DeepForest uv sync --all-extras --dev ``` -------------------------------- ### Install DeepForest from source using pip Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/install.md.txt Install DeepForest directly from its GitHub repository using pip. ```bash pip install git+https://github.com/weecology/DeepForest.git ``` -------------------------------- ### Install Comet ML Source: https://deepforest.readthedocs.io/en/stable/user_guide/examples/nest_detection.html Installs the Comet ML library, which is used for experiment tracking and model management. ```bash !pip install comet_ml ``` -------------------------------- ### Install DeepForest from source using uv Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/install.md.txt Add DeepForest from its GitHub repository to your project using uv. ```bash uv add "deepforest @ git+https://github.com/weecology/deepforest" ``` -------------------------------- ### DeepForest LR Scheduler Configuration Example Source: https://deepforest.readthedocs.io/en/stable/source/deepforest.html Example of configuring a learning rate scheduler with a monitor for schedulers like ReduceLROnPlateau. Ensure the 'monitor' metric is available when the scheduler updates. ```python lr_scheduler_config = { # REQUIRED: The scheduler instance "scheduler": lr_scheduler, # The unit of the scheduler's step size, could also be 'step'. # 'epoch' updates the scheduler on epoch end whereas 'step' # updates it after a optimizer update. "interval": "epoch", # How many epochs/steps should pass between calls to # `scheduler.step()`. 1 corresponds to updating the learning # rate after every epoch/step. "frequency": 1, # Metric to monitor for schedulers like `ReduceLROnPlateau` "monitor": "val_loss", # If set to `True`, will enforce that the value specified 'monitor' # is available when the scheduler is updated, thus stopping # training if not found. If set to `False`, it will only produce a warning "strict": True, # If using the `LearningRateMonitor` callback to monitor the # learning rate progress, this keyword can be used to specify # a custom logged name "name": None, } ``` -------------------------------- ### Initialize and Configure Training Source: https://deepforest.readthedocs.io/en/stable/user_guide/11_training.html Basic setup for loading a model and configuring training parameters using an annotation file. ```python import os from deepforest import main from deepforest import get_data # Example run with short training annotations_file = get_data("testfile_deepforest.csv") # Load the default model m = main.deepforest() m.config.train.epochs = 1 m.config.train.csv_file = annotations_file m.config.train.root_dir = os.path.dirname(annotations_file) m.create_trainer() ``` -------------------------------- ### Install deepforestr R package and DeepForest Python Source: https://deepforest.readthedocs.io/en/stable/user_guide/deepforestr.html Installs the R package from GitHub and then installs the Python environment and DeepForest package. Restart R after running these commands. ```R devtools::install_github('weecology/deepforestr') # Install the R package from GitHub deepforestr::install_deepforest() # Install Python & DeepForest; Takes ~3 minutes ``` -------------------------------- ### Verify installation Source: https://deepforest.readthedocs.io/en/stable/development/contributing.html Simple Python script to verify that DeepForest is correctly installed. ```python from deepforest import main model = main.deepforest() print("DeepForest successfully installed!") ``` -------------------------------- ### Clone and install DeepForest locally using pip Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/install.md.txt Clone the DeepForest repository and install it locally using pip. ```bash git clone https://github.com/weecology/DeepForest.git cd DeepForest pip install . ``` -------------------------------- ### Install DeepForest Source: https://deepforest.readthedocs.io/en/stable/user_guide/sample_test.html Install the DeepForest package using pip. This command installs the package from a local path. ```bash !pip install ../../ -U ``` -------------------------------- ### Execute Model Training Source: https://deepforest.readthedocs.io/en/stable/user_guide/11_training.html Start the training process using the configured model object. ```python m.trainer.fit(model) ``` -------------------------------- ### Install DeepForest using pip Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/install.md.txt Use this command to install the latest stable version of DeepForest from PyPI. ```bash pip install deepforest ``` -------------------------------- ### Test DeepForest Documentation Locally Source: https://deepforest.readthedocs.io/en/stable/development/contributing.html Navigate to the docs directory, install the current DeepForest package, clean previous builds, and build the HTML documentation. ```bash cd docs # Go to the docs directory and install the current changes. pip install ../ -U make clean # Run make html # Run ``` -------------------------------- ### Example shapefile output Source: https://deepforest.readthedocs.io/en/stable/user_guide/01_Reading_data.html Shows the expected output format after reading a shapefile. ```text label image_path geometry 0 Tree OSBS_029.tif POLYGON ((105.000 214.000, 95.000 214.000, 95.... 1 Tree OSBS_029.tif POLYGON ((205.000 214.000, 195.000 214.000, 19... ``` -------------------------------- ### Example point shapefile output Source: https://deepforest.readthedocs.io/en/stable/user_guide/01_Reading_data.html Shows the expected output format for point shapefiles. ```text label image_path geometry 0 Tree OSBS_029.tif POINT (100.000 209.000) 1 Tree OSBS_029.tif POINT (200.000 209.000) ``` -------------------------------- ### Example polygon shapefile output Source: https://deepforest.readthedocs.io/en/stable/user_guide/01_Reading_data.html Shows the expected output format for polygon shapefiles. ```text label image_path geometry 0 Tree OSBS_029.png POLYGON ((0.00000 0.00000, 0.00000 2.00000, 1.... 1 Tree OSBS_029.png POLYGON ((2.00000 2.00000, 2.00000 4.00000, 3.... ``` -------------------------------- ### Initialize and Train DeepForest Model Source: https://deepforest.readthedocs.io/en/stable/user_guide/examples/Bird_FineTuning.html Initializes the trainer with a CometLogger and fits the model. This is a basic setup for training. For demonstration, max_steps can be set to a small number. ```python model.create_trainer(logger=comet_logger) model.trainer.fit(model) ``` -------------------------------- ### Clone and Install DeepForest Source: https://deepforest.readthedocs.io/en/stable/user_guide/examples/nest_detection.html Clones the DeepForest repository from GitHub and installs it in editable mode. This is necessary to use the DeepForest library. ```bash !git clone https://github.com/weecology/DeepForest.git ``` ```bash %cd DeepForest !pip install -e . %cd .. ``` -------------------------------- ### Implement on_load_checkpoint Hook Source: https://deepforest.readthedocs.io/en/stable/source/deepforest.html Example implementation of the on_load_checkpoint hook for restoring model state. ```python def on_load_checkpoint(self, checkpoint): # 99% of the time you don't need to implement this method ``` -------------------------------- ### Development installation of DeepForest using pip Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/install.md.txt Install DeepForest in development mode with all dependencies, including dev and docs, using pip. ```bash git clone https://github.com/weecology/DeepForest.git cd DeepForest pip install .'[dev,docs]' ``` -------------------------------- ### Example Log Directory Structure Source: https://deepforest.readthedocs.io/en/stable/user_guide/11_training.html This `tree` command output illustrates the typical organization of files within a DeepForest training log directory, including checkpoints, hyperparameters, and generated images. ```bash tree pretrain/late_meadowlark_5698 ├── checkpoints │ ├── hf_weights │ │ ├── config.json │ │ ├── model.safetensors │ │ └── README.md │ ├── last.ckpt │ ├── retinanet-epoch:07-map_50:0.16.ckpt ├── hparams.yaml ├── images │ ├── predictions │ │ ├── 2018_TEAK_3_323000_4098000_image_691_11742.json │ │ ├── 2018_TEAK_3_323000_4098000_image_691_11742.png │ │ ├── 2018_TEAK_3_323000_4098000_image_691_13699.json │ │ ├── 2018_TEAK_3_323000_4098000_image_691_13699.png │ │ ├── 2018_TEAK_3_323000_4098000_image_691_23484.json │ │ ├── 2018_TEAK_3_323000_4098000_image_691_23484.png ... │ ├── train_sample │ │ ├── 2019_HOPB_3_719000_4705000_image_tile_97.png │ │ ├── 2019_SERC_4_369000_4304000_image_tile_2.png │ │ ├── 2019_SOAP_4_301000_4106000_image_tile_61.png │ │ ├── 2019_WREF_3_577000_5072000_image_tile_15.png │ │ └── 2019_WREF_3_581000_5079000_image_tile_82.png │ └── validation_sample │ ├── BLAN_009_2019.png │ ├── JERC_048_2018.png │ ├── MLBS_062_2018.png │ ├── SJER_009_2018.png │ └── SOAP_056_2019.png ├── metrics.csv ``` -------------------------------- ### Install DeepForest using uv Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/install.md.txt Use this command to add DeepForest to your project using the uv package manager. ```bash uv add deepforest ``` -------------------------------- ### Log Training and Validation Dataset Samples Source: https://deepforest.readthedocs.io/en/stable/_modules/deepforest/callbacks.html Logs sample images from the training and validation datasets at the start of training. This method is skipped if `fast_dev_run` is enabled. ```python def on_train_start(self, trainer, pl_module): """Log sample images from training and validation datasets at training start.""" if trainer.fast_dev_run: return self.trainer = trainer self.pl_module = pl_module # Training samples pl_module.print("Logging training dataset samples.") train_ds = trainer.train_dataloader.dataset self._log_dataset_sample(train_ds, split="train") # Validation samples if trainer.val_dataloaders: pl_module.print("Logging validation dataset samples.") val_ds = trainer.val_dataloaders.dataset self._log_dataset_sample(val_ds, split="validation") ``` -------------------------------- ### Retrieve sample image path with get_data Source: https://deepforest.readthedocs.io/en/stable/getting_started/intro_tutorials/load_sample_data.html Use the `get_data` helper function to locate the path to the sample data directory. This is useful for testing DeepForest examples. ```python from deepforest import get_data # Retrieve sample image path sample_image = get_data("OSBS_029.png") print(sample_image) # '[path]...../deepforest/data/OSBS_029.png' ``` -------------------------------- ### Initialize DeepForest model and predict on sample image Source: https://deepforest.readthedocs.io/en/stable/getting_started/intro_tutorials/load_sample_data.html Initialize the DeepForest model and load a pre-trained tree detection model from Hugging Face. Then, use `predict_image` to get bounding boxes from a custom image path. Ensure the model is loaded before prediction. ```python from deepforest import main, get_data # Initialize the model and load the pre-trained release model model = main.deepforest() # Load a pretrained tree detection model from Hugging Face model.load_model(model_name="weecology/deepforest-tree", revision="main") # Use predict_image to get bounding boxes from a custom image path image_path = get_data("OSBS_029.png") boxes = model.predict_image(path=image_path, return_plot=False) # Output bounding boxes print(boxes) ``` -------------------------------- ### Load Checkpoint Without num_classes (Pre-2.0) Source: https://deepforest.readthedocs.io/en/stable/user_guide/03_cropmodels.html This example shows how to load a checkpoint from DeepForest versions prior to 2.0, where num_classes was not saved. A warning will be issued if num_classes or label_dict are not provided. ```python >>> from deepforest import model >>> cropmodel = model.CropModel.load_from_checkpoint("/Users/benweinstein/3caaa23614c041eaa7edcc1231cf216b.ckpt") No model created if model or num_classes is not provided, use load_from_disk to create a model from data directory. ``` -------------------------------- ### Install DeepForest Python package Source: https://deepforest.readthedocs.io/en/stable/user_guide/deepforestr.html Installs the DeepForest Python package into your preferred Python environment using pip. This is for users who already have a Python setup. ```Python pip install DeepForest ``` -------------------------------- ### Initialize Model and Prepare Full Tile Source: https://deepforest.readthedocs.io/en/stable/user_guide/examples/Australia.html Load a pre-trained model and prepare a full-sized TIFF image for prediction. ```python m = main.deepforest() m.load_model("weecology/deepforest-tree") # Make into a 3 page, remove alpha channel, and make channels last r = rio.open("/Users/benweinstein/Downloads/Plot13Ortho.tif").read() r = r[:3, :, :] r = r.transpose(1, 2, 0) # boxes = m.predict_tile(image=r, patch_size=700, patch_overlap=0.2, iou_threshold=0.5) # boxes["image_path"] = "Plot13Ortho.tif" # gdf = utilities.boxes_to_shapefile(boxes, root_dir="/Users/benweinstein/Downloads") ``` -------------------------------- ### Initialize CropModel with Custom Resize Source: https://deepforest.readthedocs.io/en/stable/user_guide/09_configuration_file.html Instantiate the CropModel with custom image resize dimensions specified in the config_args. ```python from deepforest.model import CropModel # Or use custom resize dimensions crop_model = CropModel(config_args={"resize": [300, 300]}) ``` -------------------------------- ### Load Datasets from Disk Source: https://deepforest.readthedocs.io/en/stable/_modules/deepforest/model.html Loads training and validation datasets, sets up class mappings, and initializes the model if not already present. ```python def load_from_disk(self, train_dir, val_dir): """Load the training and validation datasets from disk. Args: train_dir (str): The directory containing the training dataset. val_dir (str): The directory containing the validation dataset. Returns: None """ self.train_ds, self.val_ds = create_aligned_image_folders( train_dir, val_dir, transform_train=self.get_transform(augmentations=["HorizontalFlip"]), transform_val=self.get_transform(augmentations=None), ) self.label_dict = self.train_ds.class_to_idx # Create a reverse mapping from numeric indices to class labels self.numeric_to_label_dict = {v: k for k, v in self.label_dict.items()} self.num_classes = len(self.label_dict) if self.model is None: self.create_model(self.num_classes) ``` -------------------------------- ### Install DeepForest package Source: https://deepforest.readthedocs.io/en/stable/_sources/getting_started/index.md.txt Use these commands to install the DeepForest package via common Python package managers. ```bash pip install deepforest ``` ```bash uv add deepforest ``` -------------------------------- ### Initialize Model from Scratch Source: https://deepforest.readthedocs.io/en/stable/user_guide/11_training.html Disable prebuilt model weights by setting the model name to None and defining custom classes. ```python m = main.deepforest(config_args{"num_classes": 3, "label_dict": { "Tree": 0, "Bird": 1, "Animal": 2 } "model":{"name":None}}) ``` -------------------------------- ### Get Box Recall Value Source: https://deepforest.readthedocs.io/en/stable/user_guide/12_evaluation.html Access the 'box_recall' key from the evaluation results to get the calculated recall value. ```python results["box_recall"] ``` -------------------------------- ### Train with Custom Configuration Source: https://deepforest.readthedocs.io/en/stable/user_guide/11_training.html Executes a training run using a specific configuration file located in a custom directory. ```bash deepforest --config-dir /your/config/folder --config-name config_file_name train ``` -------------------------------- ### Train DeepForest Model via CLI Source: https://deepforest.readthedocs.io/en/stable/user_guide/11_training.html Use this command to initiate model training. Configure dataset paths and batch size as needed. For environments using `uv`, prefix with `uv run`. ```bash deepforest train batch_size=8 train.csv_file=your_labels.csv train.root_dir=some/path ``` -------------------------------- ### Get Box Precision Value Source: https://deepforest.readthedocs.io/en/stable/user_guide/12_evaluation.html Access the 'box_precision' key from the evaluation results to get the calculated regression box precision value. ```python results["box_precision"] ``` -------------------------------- ### Install deepforestr R package from GitHub Source: https://deepforest.readthedocs.io/en/stable/user_guide/deepforestr.html Installs the development version of the deepforestr R package directly from GitHub using the remotes package. ```R remotes::install_github("weecology/deepforestr") # development version from GitHub ``` -------------------------------- ### Create model and trainer instances Source: https://deepforest.readthedocs.io/en/stable/source/deepforest.html Utility functions for initializing the model and the PyTorch Lightning trainer. ```python create_model(_num_classes_)[source] ``` ```python create_trainer(_** kwargs_)[source] ``` -------------------------------- ### Configure Multiple Optimizers in Lightning Source: https://deepforest.readthedocs.io/en/stable/source/deepforest.html Demonstrates how to return multiple optimizers and schedulers from the configure_optimizers hook. ```python def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, ) ``` -------------------------------- ### Example Dataframe Output Source: https://deepforest.readthedocs.io/en/stable/_sources/user_guide/01_Reading_data.md.txt Representation of the resulting dataframe after reading annotations. ```text image_path xmin ymin xmax ymax label geometry 0 OSBS_029.tif 203 67 227 90 Tree POLYGON ((227.000 67.000, 227.000 90.000, 203.... 1 OSBS_029.tif 256 99 288 140 Tree POLYGON ((288.000 99.000, 288.000 140.000, 256... 2 OSBS_029.tif 166 253 225 304 Tree POLYGON ((225.000 253.000, 225.000 304.000, 16... 3 OSBS_029.tif 365 2 400 27 Tree POLYGON ((400.000 2.000, 400.000 27.000, 365.0... 4 OSBS_029.tif 312 13 349 47 Tree POLYGON ((349.000 13.000, 349.000 47.000, 312.... ``` -------------------------------- ### Upload CropModel to Hugging Face Hub Source: https://deepforest.readthedocs.io/en/stable/development/contributing.html Instantiate a CropModel, push it to the Hugging Face Hub under a specified name (e.g., 'weecology/cropmodel-deadtrees'), and demonstrate how to reload it later. Model names should reflect the classification task. ```python from deepforest.model import CropModel crop_model = CropModel() crop_model.push_to_hub("weecology/cropmodel-deadtrees") # Reload it later crop_model.from_pretrained("Weecology/cropmodel-deadtrees") ``` -------------------------------- ### Initialize Model and Metrics Source: https://deepforest.readthedocs.io/en/stable/_modules/deepforest/model.html Configures the model architecture and initializes TorchMetrics for accuracy and precision evaluation. ```python def create_model(self, num_classes): """Create a model with the given number of classes.""" self.accuracy = torchmetrics.Accuracy( average="none", num_classes=num_classes, task="multiclass" ) self.total_accuracy = torchmetrics.Accuracy( num_classes=num_classes, task="multiclass" ) self.precision_metric = torchmetrics.Precision( num_classes=num_classes, task="multiclass" ) self.macro_precision = torchmetrics.Precision( num_classes=num_classes, task="multiclass", average="macro" ) self.metrics = torchmetrics.MetricCollection( { "Class Accuracy": self.accuracy, "Accuracy": self.total_accuracy, "Precision": self.precision_metric, "Macro Precision": self.macro_precision, } ) self.model = simple_resnet_50(num_classes=num_classes) ``` -------------------------------- ### CSV point data format Source: https://deepforest.readthedocs.io/en/stable/user_guide/01_Reading_data.html Example of a CSV file structure for point data. ```csv x,y,label 10,20,Tree 15,30,Tree ``` -------------------------------- ### Initialize and Use Single Crop Model Source: https://deepforest.readthedocs.io/en/stable/user_guide/03_cropmodels.html Demonstrates initializing a CropModel with a specified number of classes and applying it with predict_tile. Ensure the trainer is created before prediction. ```python import pandas as pd from deepforest import model from deepforest import main as m from deepforest.utilities import get_data df = pd.read_csv(get_data("testfile_multi.csv")) crop_model = model.CropModel(num_classes=2) # Or set up the crop model or load weights model.CropModel.load_from_checkpoint() m.create_trainer() result = m.predict_tile(path=path, crop_model=crop_model) ``` -------------------------------- ### Configure Training Performance Parameters Source: https://deepforest.readthedocs.io/en/stable/user_guide/11_training.html Adjust configuration settings to optimize data loading and memory usage during training. Always call m.create_trainer() after modifying these settings. ```python m.config.workers = 5 ``` ```python m.configpreload_images = True ``` ```python m.config.batch_size = 10 ``` -------------------------------- ### Train a CropModel Source: https://deepforest.readthedocs.io/en/stable/user_guide/03_cropmodels.html Initializes a trainer and fits the model using data loaded from disk. ```python from deepforest.model import CropModel crop_model.create_trainer(fast_dev_run=True) # Get the data stored from the write_crops step above. crop_model.load_from_disk(train_dir=tmpdir, val_dir=tmpdir) crop_model.trainer.fit(crop_model) crop_model.trainer.validate(crop_model) ``` -------------------------------- ### Implement ReduceLROnPlateau in configure_optimizers Source: https://deepforest.readthedocs.io/en/stable/source/deepforest.html Example of configuring an optimizer with a ReduceLROnPlateau scheduler that requires a monitored metric. ```python # The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } ``` -------------------------------- ### CSV polygon data format Source: https://deepforest.readthedocs.io/en/stable/user_guide/01_Reading_data.html Example of a CSV file structure for polygons using WKT format. ```csv "POLYGON ((0 0, 0 2, 1 1, 1 0, 0 0))",Tree,OSBS_029.png "POLYGON ((2 2, 2 4, 3 3, 3 2, 2 2))",Tree,OSBS_029.png ``` -------------------------------- ### Example GeoDataFrame Row Source: https://deepforest.readthedocs.io/en/stable/_sources/user_guide/01_Reading_data.md.txt Represents a single row from a GeoDataFrame, showing geometry, label, and image path. ```text geometry POLYGON ((404222.4 3285121.5, 404222.4 3285122... label Tree image_path /Users/benweinstein/Documents/DeepForest/deepf... Name: 0, dtype: object ``` -------------------------------- ### Initialize SGD Optimizer Source: https://deepforest.readthedocs.io/en/stable/user_guide/09_configuration_file.html Configure the stochastic gradient descent optimizer with momentum for training. ```python from torch import optim optim.SGD(self.model.parameters(), lr=self.config.train.lr, momentum=0.9) ``` -------------------------------- ### Initialize Plotting Source: https://deepforest.readthedocs.io/en/stable/user_guide/examples/Australia.html Initializes a matplotlib figure and axes for plotting geospatial data. This is a common setup for visualization. ```python fig, ax = plt.subplots(1, 1, figsize=(10, 10)) ``` -------------------------------- ### Initialize CropModel with Default Resize Source: https://deepforest.readthedocs.io/en/stable/user_guide/09_configuration_file.html Instantiate the CropModel using default image resize dimensions of 224x224. ```python from deepforest.model import CropModel # Use default 224x224 resize crop_model = CropModel() ``` -------------------------------- ### Validate training configuration Source: https://deepforest.readthedocs.io/en/stable/_modules/deepforest/main.html Ensures that a training CSV file is defined in the configuration before starting the training process. ```python def on_fit_start(self): if self.config.train.csv_file is None: raise AttributeError( "Cannot train with a train annotations file, " "please set 'config['train']['csv_file'] before " "calling deepforest.create_trainer()'" ) ``` -------------------------------- ### Run tests locally Source: https://deepforest.readthedocs.io/en/stable/development/contributing.html Commands to upgrade the package and execute the test suite. ```bash $ pip install . --upgrade # or python setup.py install $ pytest -v ``` -------------------------------- ### Initialize DeepForest with configuration arguments Source: https://deepforest.readthedocs.io/en/stable/_sources/user_guide/02_prebuilt.md.txt Use a dictionary to specify model parameters when initializing the DeepForest object. ```python config_args = { "model": {"name": "weecology/deepforest-livestock"} } m = main.deepforest(config_args=config_args) ``` -------------------------------- ### Example CSV Data for Points Source: https://deepforest.readthedocs.io/en/stable/_sources/user_guide/01_Reading_data.md.txt Illustrates the CSV format for point annotations, including x, y coordinates and a label. ```text x,y,label 10,20,Tree 15,30,Tree ``` -------------------------------- ### CSV Annotation Format Source: https://deepforest.readthedocs.io/en/stable/_sources/user_guide/01_Reading_data.md.txt Example structure for a CSV file containing box coordinates relative to the image origin. ```csv image_path,xmin,ymin,xmax,ymax,label OSBS_029.tif,203,67,227,90,Tree OSBS_029.tif,256,99,288,140,Tree OSBS_029.tif,166,253,225,304,Tree OSBS_029.tif,365,2,400,27,Tree OSBS_029.tif,312,13,349,47,Tree OSBS_029.tif,365,21,400,70,Tree OSBS_029.tif,278,1,312,37,Tree OSBS_029.tif,364,204,400,246,Tree ``` -------------------------------- ### Load a Trained Model Source: https://deepforest.readthedocs.io/en/stable/user_guide/03_cropmodels.html Initialize a CropModel from a saved checkpoint file. ```python from deepforest.model import CropModel from pytorch_lightning import Trainer from torchvision.datasets import ImageFolder import numpy as np # Load a trained model from checkpoint cropmodel = CropModel.load_from_checkpoint("path/to/checkpoint.ckpt") # The model will automatically load: # - The model architecture and weights # - The label dictionary mapping class names to indices # - The number of classes # - Any hyperparameters saved during training ``` -------------------------------- ### Get Data Transformation Pipeline Source: https://deepforest.readthedocs.io/en/stable/source/deepforest.html Retrieves the data transformation pipeline configured for the model, optionally applying specified augmentations. ```APIDOC ## get_transform(_augmentations_) ### Description Returns the data transformation pipeline for the model. ### Method GET ### Endpoint /get_transform ### Parameters #### Path Parameters None #### Query Parameters - **augmentations** (str, list, dict, optional) - Augmentation configuration. If None, no augmentations are applied. If ‘HorizontalFlip’ or [‘HorizontalFlip’], applies random horizontal flip. ### Request Example ```json { "augmentations": "HorizontalFlip" } ``` ### Response #### Success Response (200) - **transform_pipeline** (torchvision.transforms.Compose) - The composed data transformation pipeline. #### Response Example ```json { "transform_pipeline": "compose_object" } ``` ``` -------------------------------- ### Loading a custom dataset Source: https://deepforest.readthedocs.io/en/stable/user_guide/05_model_architecture.html Demonstrates how to initialize a DeepForest model and load a dataset using the built-in load_dataset method. ```python from deepforest import main m = main.deepforest() existing_loader = m.load_dataset(csv_file=m.config.train.csv_file, root_dir=m.config.train.root_dir, batch_size=m.config.batch_size) ``` -------------------------------- ### Example DataFrame Output Source: https://deepforest.readthedocs.io/en/stable/_sources/user_guide/01_Reading_data.md.txt Displays the head of a DataFrame after reading a shapefile, showing columns for label, image path, and geometry. ```text label image_path geometry 0 Tree OSBS_029.tif POLYGON ((0.00000 0.00000, 0.00000 2.00000, 1.... 1 Tree OSBS_029.tif POLYGON ((2.00000 2.00000, 2.00000 4.00000, 3.... ``` -------------------------------- ### Model Validation Results Output Source: https://deepforest.readthedocs.io/en/stable/user_guide/12_evaluation.html Example output dictionary containing IoU, mAP, and loss metrics after running model validation. ```text classes 0.0 iou 0.6305446564807566 iou/cl_0 0.6305446564807566 map 0.04219449311494827 map_50 0.11141198128461838 map_75 0.025357535108923912 map_large -1.0 map_medium 0.05097917467355728 map_per_class -1.0 map_small 0.0 mar_1 0.008860759437084198 mar_10 0.03417721390724182 mar_100 0.08481013029813766 mar_100_per_class -1.0 mar_large -1.0 mar_medium 0.09436620026826859 mar_small 0.0 val_bbox_regression 0.5196723341941833 val_classification 0.4998389184474945 ``` -------------------------------- ### Epoch Start Validation Source: https://deepforest.readthedocs.io/en/stable/_modules/deepforest/main.html The `on_validation_epoch_start` method is a hook that runs at the beginning of each validation epoch, typically used for resetting prediction lists. ```APIDOC ## Epoch Start Validation ### Description Initializes or resets necessary attributes at the start of a validation epoch, such as the predictions list. ### Method N/A (This is a hook method within a class, not a direct API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```python # Example usage within the library (not a direct API call) self.on_validation_epoch_start() ``` ### Response #### Success Response (200) N/A (This method does not return a value; it modifies internal state.) ``` -------------------------------- ### Importing Pascal VOC Annotations Source: https://deepforest.readthedocs.io/en/stable/_sources/user_guide/01_Reading_data.md.txt Load object detection annotations provided in Pascal VOC XML format. ```python from deepforest import utilities df = utilities.read_file(input="/path/to/pascal_voc_annotations.xml") df.head() ``` -------------------------------- ### Reset Predictions at Epoch Start Source: https://deepforest.readthedocs.io/en/stable/_modules/deepforest/main.html Resets the predictions list at the beginning of each validation epoch. This ensures that predictions are collected per epoch. ```python def on_validation_epoch_start(self): self.predictions = [] ``` -------------------------------- ### Download Progress Bar Source: https://deepforest.readthedocs.io/en/stable/_modules/deepforest/utilities.html A tqdm-based progress bar class for tracking download progress. ```python class DownloadProgressBar(tqdm): """Download progress bar class.""" def update_to(self, b=1, bsize=1, tsize=None): """ Update class attributes Args: b: bsize: tsize: Returns: """ if tsize is not None: self.total = tsize self.update(b * bsize - self.n) ```