### Install FuseMedML from PyPI with examples
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
Installs FuseMedML from PyPI including all examples.
```bash
pip install fuse-med-ml[all,examples]
```
--------------------------------
### Install FuseMedML from source with examples
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
Installs FuseMedML in editable mode including all examples.
```bash
pip install -e .[all,examples]
```
--------------------------------
### Install FuseMedML
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/multimodality/image_clinical/multimodality_image_clinical.ipynb
Clones the FuseMedML repository and installs it with all example dependencies. It's recommended to run this in a Google Colab environment with GPU support enabled.
```python
!git clone https://github.com/IBM/fuse-med-ml.git
%cd fuse-med-ml
!pip install -e .[all,examples]
```
--------------------------------
### Install PyTorch with CUDA support
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
Example command to install PyTorch with specific CUDA version.
```bash
conda install pytorch torchvision torchaudio pytorch-cuda=11.6 -c pytorch -c nvidia
```
--------------------------------
### Caching Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/data/README.md
An example demonstrating how to enable caching for the data pipeline. It shows the creation of a SamplesCacher and its integration into the DatasetDefault.
```python
static_pipeline = PipelineDefault("static", [
(OpKits21SampleIDDecode(), dict()), # will save image and seg path to "data.input.img_path", "data.gt.seg_path"
(OpLoadImage(data_dir), dict(key_in="data.input.img_path", key_out="data.input.img", format="nib")),
(OpLoadImage(data_dir), dict(key_in="data.gt.seg_path", key_out="data.gt.seg", format="nib")),
(OpClip(), dict(key="data.input.img", clip=(-500, 500))),
(OpToRange(), dict(key="data.input.img", from_range=(-500, 500), to_range=(0, 1))),
])
cacher = SamplesCacher(unique_cacher_name,
static_pipeline,
cache_dirs=cache_dir) #it can just one path for the cache ot list of paths which will be tried in order, moving the next when available space is exausted.
sample_ids= list(range(10))
my_dataset = DatasetDefault(sample_ids=sample_ids,
static_pipeline=static_pipeline,
dynamic_pipeline=None,
cacher=cacher,
)
my_dataset.create()
```
--------------------------------
### Install FuseMedML
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/hello_world/hello_world.ipynb
Installs FuseMedML and its dependencies. It includes a workaround for a Colab issue requiring a runtime restart after installation.
```python
# @title 1. Install FuseMedML
# @markdown Please choose whether or not to install FuseMedML and execute this cell by pressing the *Play* button on the left.
install_fuse = False # @param {type:"boolean"}
use_gpu = True # @param {type:"boolean"}
# @markdown ### **Warning!**
# @markdown If you wish to install FuseMedML -- as a workaround for
# @markdown [this](https://stackoverflow.com/questions/57831187/need-to-restart-runtime-before-import-an-installed-package-in-colab)
# @markdown issue please follow those steps:
# @markdown 1. Execute this cell by pressing the ▶️ button on the left.
# @markdown 2. Restart runtime
# @markdown 3. Execute it once again
# @markdown 4. Enjoy
if install_fuse:
!git clone https://github.com/BiomedSciAI/fuse-med-ml.git
%cd fuse-med-ml
%pip install -e .[all,examples]
```
--------------------------------
### Install Required Packages
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/oai_example/README.md
Installs the project dependencies, including the MCP CLI, for the workflow.
```bash
pip install -e .[examples]
pip install "mcp[cli]"
```
--------------------------------
### Basic Example - Static Pipeline
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/data/README.md
A basic example demonstrating a static pipeline that loads and pre-processes an image and its corresponding segmentation map. It shows how to create a pipeline from a list of operators and arguments, and how to initialize a dataset with this pipeline.
```python
static_pipeline = PipelineDefault("static", [
# decoding sample ID
(OpKits21SampleIDDecode(), dict()), # will save image and seg path to "data.input.img_path", "data.gt.seg_path"
# loading data
(OpLoadImage(data_dir), dict(key_in="data.input.img_path", key_out="data.input.img", format="nib")),
(OpLoadImage(data_dir), dict(key_in="data.gt.seg_path", key_out="data.gt.seg", format="nib")),
# fixed image normalization
(OpClip(), dict(key="data.input.img", clip=(-500, 500))),
(OpToRange(), dict(key="data.input.img", from_range=(-500, 500), to_range=(0, 1))),
])
sample_ids= list(range(10))
my_dataset = DatasetDefault(sample_ids=sample_ids,
static_pipeline=static_pipeline,
dynamic_pipeline=None,
cacher=None,
)
my_dataset.create()
```
--------------------------------
### Training Setup
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/hello_world/hello_world.ipynb
Configures the optimizer, learning rate scheduler, and PyTorch Lightning module for training.
```python
# create optimizer
optimizer = optim.Adam(model.parameters(), lr=train_params["opt.lr"], weight_decay=train_params["opt.weight_decay"])
# create scheduler
lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer)
lr_sch_config = dict(scheduler=lr_scheduler, monitor="validation.losses.total_loss")
# optimizer and lr sch - see pl.LightningModule.configure_optimizers return value for all options
optimizers_and_lr_schs = dict(optimizer=optimizer, lr_scheduler=lr_sch_config)
# create instance of PL module - FuseMedML generic version
pl_module = LightningModuleDefault(
model_dir=paths["model_dir"],
model=model,
losses=losses,
train_metrics=train_metrics,
validation_metrics=validation_metrics,
best_epoch_source=best_epoch_source,
optimizers_and_lr_schs=optimizers_and_lr_schs,
)
# create lightning trainer
pl_trainer = pl.Trainer(
default_root_dir=paths["model_dir"],
max_epochs=train_params["trainer.num_epochs"],
accelerator=train_params["trainer.accelerator"],
devices=train_params["trainer.num_devices"],
)
# train
pl_trainer.fit(pl_module, train_dataloader, validation_dataloader, ckpt_path=train_params["trainer.ckpt_path"])
```
--------------------------------
### Install FuseMedML from source (recommended)
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
Installs FuseMedML in editable mode with all domain extensions.
```bash
pip install -e .[all]
```
--------------------------------
### Install FuseMedML from PyPI
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
Installs FuseMedML from PyPI with all domain extensions.
```bash
pip install fuse-med-ml[all]
```
--------------------------------
### Install development requirements
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/CONTRIBUTING.md
Installs the necessary libraries for development, including formatting and linting tools, if not already installed.
```bash
$ pip install -e .[all]
```
--------------------------------
### Setup Logger and Dataset Size
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/multimodality/image_clinical/multimodality_image_clinical.ipynb
Configures the CUDA visible devices, starts the FuseMedML logger, and defines variables for dataset size, model directory, cache directory, and data directory. It also includes options to reset the cache and split file.
```python
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import logging
from fuse.utils.utils_logger import fuse_logger_start
fuse_logger_start(output_path=None, console_verbose_level=logging.INFO)
all_data = False # use all data or just 400 samples
model_dir = "model_dir" # path to model dir
cache_dir = "cache_dir" # path to cache dir
data_dir = "data_dir"
reset_cache = True
reset_split_file = True
```
--------------------------------
### Evaluating dummy example predictions
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/classification/bright/README.md
Command to evaluate dummy example predictions and targets using the evaluation script.
```bash
cd fuse_examples/imaging/classification/knight/eval
python eval.py example/example_targets.csv example/example_task1_predictions.csv example/example_task2_predictions.csv example/results
```
--------------------------------
### NDict Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
An example of how to use NDict to store data in a nested dictionary structure, which is a key aspect of FuseMedML's flexibility.
```python
from fuse.utils import NDict
sample_ndict = NDict()
sample_ndict['input.mri'] = # ...
sample_ndict['input.ct_view_a'] = # ...
sample_ndict['input.ct_view_b'] = # ...
sample_ndict['groundtruth.disease_level_label'] = # ...
```
--------------------------------
### ModelWrapSeqToDict Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/dl/README.md
Example of wrapping a PyTorch model using ModelWrapSeqToDict for use in FuseMedML, including input/output keys and post-processing.
```python
model = ModelWrapSeqToDict(
model=torch_model,
model_inputs=["data.image"],
post_forward_processing_function=perform_softmax,
model_outputs=["model.logits.classification", "model.output.classification"],
)
```
--------------------------------
### CustomLightningModule Instantiation
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/dl/README.md
Example of instantiating a custom LightningModule for flexible and custom DL training.
```python
pl_module = CustomLightningModule(**custom_args)
```
--------------------------------
### Download Kits21 Data
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuseimg/datasets/kits21_example.ipynb
Downloads a specified number of samples from the Kits21 dataset to a local directory.
```python
num_samples = 2
data_dir = os.environ["KITS21_DATA_PATH"] if "KITS21_DATA_PATH" in os.environ else mkdtemp(prefix="kits21_data")
KITS21.download(data_dir, cases=list(range(num_samples)))
```
--------------------------------
### Hydra Overrides
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/oai_example/README.md
Examples of overriding default parameters in Hydra configurations using command-line arguments.
```bash
python fuse_examples/imaging/oai_example/self_supervised/dino.py batch_size=16
```
```bash
python fuse_examples/imaging/oai_example/self_supervised/dino.py batch_size=16 lr=0.001
```
--------------------------------
### Creating dataloader and balanced dataloader
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/data/README.md
Example of creating a dataloader with a balanced batch sampler for a dataset.
```python
batch_sampler = BatchSamplerDefault(dataset=dataset,
balanced_class_name='data.label',
num_balanced_classes=num_classes,
batch_size=batch_size,
mode="approx",
balanced_class_weights=[1 / num_classes] * num_classes)
dataloader = DataLoader(dataset=dataset, collate_fn=CollateDefault(), batch_sampler=batch_sampler, shuffle=False, drop_last=False)
```
--------------------------------
### Run Baseline Model Training
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/classification/knight/README.md
Command to train and evaluate the baseline model.
```python
python baseline/fuse_baseline.py
```
--------------------------------
### Inference Execution
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/hello_world/hello_world.ipynb
Sets up directories, loads the model, creates a trainer, and performs inference.
```python
# setting dir and paths
create_dir(paths["inference_dir"])
infer_file = os.path.join(paths["inference_dir"], infer_common_params["infer_filename"])
checkpoint_file = os.path.join(paths["model_dir"], infer_common_params["checkpoint"])
# creating a dataloader
validation_dataloader = DataLoader(dataset=validation_dataset, collate_fn=CollateDefault(), batch_size=2, num_workers=2)
# load pytorch lightning module
model = create_model()
pl_module = LightningModuleDefault.load_from_checkpoint(
checkpoint_file, model_dir=paths["model_dir"], model=model, map_location="cpu", strict=True
)
# set the prediction keys to extract (the ones used be the evaluation function).
pl_module.set_predictions_keys(
["model.output.classification", "data.label"]
) # which keys to extract and dump into file
# create a trainer instance
pl_trainer = pl.Trainer(
default_root_dir=paths["model_dir"],
accelerator=infer_common_params["trainer.accelerator"],
devices=infer_common_params["trainer.num_devices"],
)
# predict
predictions = pl_trainer.predict(pl_module, validation_dataloader, return_predictions=True)
# convert list of batch outputs into a dataframe
infer_df = convert_predictions_to_dataframe(predictions)
save_dataframe(infer_df, infer_file)
```
--------------------------------
### LossDefault Usage in MNIST Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/dl/README.md
Example of using LossDefault for classification loss in the MNIST example.
```python
losses = {
"cls_loss": LossDefault(
pred="model.logits.classification", target="data.label", callable=F.cross_entropy, weight=1.0
),
}
```
--------------------------------
### Launch Inference CLI
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/oai_example/README.md
Launches the interactive inference workflow CLI.
```bash
python fuse_examples/imaging/oai_example/mcp_inference/inference_cli.py
```
--------------------------------
### Custom FuseMedML Component Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
An example of a custom data processing operator (OpPad) that can be added to FuseMedML pipelines.
```python
class OpPad(OpBase):
def __call__(self, sample_dict: NDict,
key_in: str,
padding: List[int], fill: int = 0, mode: str = 'constant',
key_out:Optional[str]=None,
):
# we extract the element in the defined key location (for example 'input.xray_img')
img = sample_dict[key_in]
assert isinstance(img, np.ndarray), f'Expected np.ndarray but got {type(img)}'
processed_img = np.pad(img, pad_width=padding, mode=mode, constant_values=fill)
# store the result in the requested output key (or in key_in if no key_out is provided)
key_out = key_in if key_out is None
sample_dict[key_out] = processed_img
# returned the modified nested dict
return sample_dict
```
--------------------------------
### Create and Run Evaluator
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/hello_world/hello_world.ipynb
Instantiates the EvaluatorDefault and runs the evaluation process.
```python
# create evaluator
evaluator = EvaluatorDefault()
# run eval
results = evaluator.eval(
ids=None,
data=os.path.join(paths["inference_dir"], eval_common_params["infer_filename"]),
metrics=metrics,
output_dir=paths["eval_dir"],
silent=False,
)
print("Done!")
```
--------------------------------
### Launch Inference CLI with Custom Config and Device
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/oai_example/README.md
Launches the inference CLI, specifying a custom configuration file and device.
```bash
python fuse_examples/imaging/oai_example/mcp_inference/inference_cli.py \
--inference-config fuse_examples/imaging/oai_example/mcp_inference/inference_config.yaml \
--device auto
```
--------------------------------
### Example Metric
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/README.md
An example of a metric component that can be used within FuseMedML, specifying input prediction and target keys.
```python
MetricAUCROC(
pred='model.output', # input - model prediction scores
target='data.label' # input - ground truth labels
)
```
--------------------------------
### Basic Meta Ops for Dataset Creation
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuseimg/datasets/kits21_example.ipynb
This snippet shows how to use OpRepeat with OpToTensor to prepare data for a dataset, avoiding boilerplate by repeating operations for different keys.
```python
repeat_for = [dict(key="data.input.img"), dict(key="data.gt.seg")]
dynamic_pipeline = PipelineDefault(
"dynamic",
[
(OpClip(), dict(key="data.input.img", clip=(-500, 500))),
(OpToRange(), dict(key="data.input.img", from_range=(-500, 500), to_range=(0, 1))),
(OpRepeat(OpToTensor(), kwargs_per_step_to_add=repeat_for), dict(dtype=torch.float32)),
],
)
```
```python
my_dataset = DatasetDefault(
sample_ids=sample_ids,
static_pipeline=static_pipeline,
dynamic_pipeline=dynamic_pipeline,
cacher=cacher,
)
my_dataset.create()
```
```python
isinstance(my_dataset[0]["data.gt.seg"], torch.Tensor)
```
--------------------------------
### Group Analysis Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/eval/README.md
Example of using the GroupAnalysis class to evaluate metrics according to feature groups, such as 'gender'.
```python
metrics = OrderedDict([
("auc_per_group", GroupAnalysis(MetricAUCROC(pred="pred", target="target"), group="gender"))
])
```
--------------------------------
### Print Sample Data
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/multimodality/image_clinical/multimodality_image_clinical.ipynb
Prints a sample from the training dataloader at a specified index.
```python
sample_index = 10
print(train_dl.dataset[sample_index])
```
--------------------------------
### Per-Fold Computation Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/eval/README.md
Example of evaluating multiple data splits/folds separately by setting the group name to '{predictions_key_name}.evaluator_fold'.
```python
data = {"pred": [prediction_fold0_filename, prediction_fold1_filename], "target": targets_filename}
# list of metrics
metrics = OrderedDict([
("auc_per_fold", GroupAnalysis(MetricAUCROC(pred="pred", target="target"), group="pred.evaluator_fold"))
])
```
--------------------------------
### TensorBoard Monitoring
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/oai_example/README.md
Command to run TensorBoard for viewing losses and metrics.
```bash
tensorboard --logdir=
```
--------------------------------
### ModelMultiHead Example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/dl/README.md
Example of using ModelMultiHead with a 3D ResNet backbone and a 3D classification head for medical image analysis.
```python
model = ModelMultiHead(
conv_inputs=(("data.input.img", 1),),
backbone=BackboneResnet3D(in_channels=1),
heads=[
Head3D(
head_name="classification",
mode="classification",
conv_inputs=[("model.backbone_features", 512)],
dropout_rate=imaging_dropout,
append_dropout_rate=clinical_dropout,
fused_dropout_rate=fused_dropout,
num_outputs=2,
append_features=[("data.input.clinical", 8)],
append_layers_description=(256, 128),
),
],
)
```
--------------------------------
### Optimizer and learning rate scheduler configuration
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/multimodality/image_clinical/multimodality_image_clinical.ipynb
Sets up the Adam optimizer and a ReduceLROnPlateau learning rate scheduler.
```python
# create optimizer
optimizer = optim.Adam(model.parameters(), lr=1e-5, weight_decay=0.001)
# create scheduler
lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer)
lr_sch_config = dict(scheduler=lr_scheduler, monitor="validation.losses.total_loss")
# optimizier and lr sch - see pl.LightningModule.configure_optimizers return value for all options
optimizers_and_lr_schs = dict(optimizer=optimizer, lr_scheduler=lr_sch_config)
```
--------------------------------
### Output paths configuration
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/hello_world/hello_world.ipynb
Defines and configures output directories for model checkpoints, caching, inference, and evaluation results.
```python
ROOT = "_examples/mnist"
model_dir = os.path.join(ROOT, "model_dir")
PATHS = {
"model_dir": model_dir,
"cache_dir": os.path.join(ROOT, "cache_dir"),
"inference_dir": os.path.join(model_dir, "infer_dir"),
"eval_dir": os.path.join(model_dir, "eval_dir"),
}
paths = PATHS
```
--------------------------------
### Meta Ops with Data Augmentation
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuseimg/datasets/kits21_example.ipynb
This snippet extends the previous example by incorporating data augmentation (OpAugAffine2D) using OpSampleAndRepeat, applying identical transformations to both image and segmentation map.
```python
dynamic_pipeline = PipelineDefault(
"dynamic",
[
(OpClip(), dict(key="data.input.img", clip=(-500, 500))),
(OpToRange(), dict(key="data.input.img", from_range=(-500, 500), to_range=(0, 1))),
(OpRepeat(OpToTensor(), kwargs_per_step_to_add=repeat_for), dict(dtype=torch.float32)),
(
OpSampleAndRepeat(OpAugAffine2D(), kwargs_per_step_to_add=repeat_for),
dict(
rotate=Uniform(-180.0, 180.0),
scale=Uniform(0.8, 1.2),
flip=(RandBool(0.5), RandBool(0.5)),
translate=(RandInt(-15, 15), RandInt(-15, 15)),
),
),
],
)
my_dataset = DatasetDefault(
sample_ids=sample_ids,
static_pipeline=static_pipeline,
dynamic_pipeline=dynamic_pipeline,
cacher=cacher,
)
my_dataset.create()
```
```python
f"min = {torch.min(my_dataset[0]['data.input.img'])} | max = {torch.max(my_dataset[0]['data.input.img'])}"
```
--------------------------------
### Create and train a PyTorch Lightning module
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/multimodality/image_clinical/multimodality_image_clinical.ipynb
This snippet shows how to instantiate a LightningModuleDefault, configure a PyTorch Lightning Trainer, and initiate the training process.
```python
pl_module = LightningModuleDefault(
model_dir=model_dir,
model=model,
losses=losses,
train_metrics=train_metrics,
validation_metrics=validation_metrics,
best_epoch_source=best_epoch_source,
optimizers_and_lr_schs=optimizers_and_lr_schs,
)
# create lightining trainer.
pl_trainer = pl.Trainer(default_root_dir=model_dir, max_epochs=2, accelerator="gpu", devices=1)
# train
pl_trainer.fit(pl_module, train_dl, validation_dl)
```
--------------------------------
### Self-Supervised Pre-training with DINO
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/oai_example/README.md
Command to initiate DINO pre-training for self-supervised learning on medical imaging data.
```bash
python fuse_examples/imaging/oai_example/self_supervised/dino.py
```
--------------------------------
### Import necessary libraries for KITS21 dataset example
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuseimg/datasets/kits21_example.ipynb
Imports required modules from the fuse.data, fuse.utils, and fuseimg libraries for dataset operations, pipeline management, and image processing specific to the KITS21 dataset.
```python
import os
from tempfile import mkdtemp
import numpy as np
import torch
from fuse.data.datasets.caching.samples_cacher import SamplesCacher
from fuse.data.datasets.dataset_default import DatasetDefault
from fuse.data.ops.ops_aug_common import OpSampleAndRepeat
from fuse.data.ops.ops_cast import OpToTensor
from fuse.data.ops.ops_common import OpLambda, OpRepeat
from fuse.data.pipelines.pipeline_default import PipelineDefault
from fuse.utils.rand.param_sampler import RandBool, RandInt, Uniform
from fuseimg.data.ops.aug.geometry import OpAugAffine2D
from fuseimg.data.ops.color import OpClip, OpToRange
from fuseimg.data.ops.image_loader import OpLoadImage
from fuseimg.datasets.kits21 import KITS21, OpKits21SampleIDDecode
```
--------------------------------
### LightningModuleDefault Instantiation
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse/dl/README.md
Example of instantiating LightningModuleDefault for supervised learning use-cases.
```python
pl_module = LightningModuleDefault(model_dir=model_dir,
model=model,
losses=losses,
train_metrics=train_metrics,
validation_metrics=validation_metrics,
best_epoch_source=best_epoch_source,
optimizers_and_lr_schs=optimizers_and_lr_schs)
```
--------------------------------
### Training common parameters
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/hello_world/hello_world.ipynb
Sets common parameters for training, including batch size, number of workers for data loaders, trainer epochs, devices, accelerator, and optimizer settings.
```python
TRAIN_COMMON_PARAMS = {}
### Data ###
TRAIN_COMMON_PARAMS["data.batch_size"] = 100
TRAIN_COMMON_PARAMS["data.train_num_workers"] = 8
TRAIN_COMMON_PARAMS["data.validation_num_workers"] = 8
### PL Trainer ###
TRAIN_COMMON_PARAMS["trainer.num_epochs"] = 2
TRAIN_COMMON_PARAMS["trainer.num_devices"] = 1
TRAIN_COMMON_PARAMS["trainer.accelerator"] = "gpu" if use_gpu else "cpu"
TRAIN_COMMON_PARAMS["trainer.ckpt_path"] = None # path to the checkpoint you wish continue the training from
### Optimizer ###
TRAIN_COMMON_PARAMS["opt.lr"] = 1e-4
TRAIN_COMMON_PARAMS["opt.weight_decay"] = 0.001
train_params = TRAIN_COMMON_PARAMS
```
--------------------------------
### Image Shape
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuseimg/datasets/kits21_example.ipynb
Displays the shape of the pre-processed image data for the first sample.
```python
my_dataset[0]["data.input.img"].shape
```
--------------------------------
### Model Creation
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/hello_world/hello_world.ipynb
Builds a LeNet model and wraps it with Fuse's component for automatic input/output handling.
```python
def create_model():
torch_model = LeNet()
# wrap basic torch model to automatically read inputs from batch_dict and save its outputs to batch_dict
model = ModelWrapSeqToDict(
model=torch_model,
model_inputs=["data.image"],
post_forward_processing_function=perform_softmax,
model_outputs=["model.logits.classification", "model.output.classification"],
)
return model
model = create_model()
```
--------------------------------
### Running the evaluation script
Source: https://github.com/biomedsciai/fuse-med-ml/blob/master/fuse_examples/imaging/classification/bright/README.md
Command to run the evaluation script for the BRIGHT challenge.
```bash
cd fuse_examples/imaging/classification/knight/eval
python eval.py