Data Preparation
Our data preparation workflow begins with the systematic extraction of images from archival datasets, specifically CrossValidation.zip and HoldOut.zip. Utilizing Python's zipfile module ensures efficient and reliable decompression. Depending on the analytical focus—whether at the patch-level or patient-level—we extract either Annotated.zip or Cropped.zip from the CrossValidation.zip archive. The images are carefully deposited into designated directories, namely EXTRACT_annotated or EXTRACT_cropped, to streamline subsequent data handling processes.
Post-extraction, the images, initially nested within patient-specific directories, are reorganized to create a flattened directory structure. This involves renaming and relocating files, employing a consistent naming convention that combines patient identifiers with sequence numbers. Flattening the directory hierarchy is crucial as it facilitates more straightforward data access patterns during model training, thus enhancing computational efficiency.
To curate datasets that are both relevant and high-quality for training, we apply rigorous filtering criteria. For patch-level images, we ensure inclusion by cross-referencing image filenames with records in HP_WSI-CoordAnnotatedPatches.xlsx, thereby guaranteeing that only images with valid annotations are selected. At the patient-level, we utilize density information from PatientDiagnosis_cropped.csv to select patients exhibiting specific histopathological characteristics, thereby aligning the dataset with the intended diagnostic objectives.
Annotation files undergo meticulous processing to produce structured CSV files required for training. In TRAIN_DATA_annotated.csv, we ensure a comprehensive mapping between images and their corresponding patch-level annotations. For patient-level data encapsulated in TRAIN_DATA_cropped.csv, we transform the 'DENSITAT' field into binary labels (0 or 1). This binarization is essential as it reformulates the problem into a binary classification task, simplifying the model's output layer design and aligning with binary cross-entropy loss functions.
Recognizing that data quality is paramount, we implement robust data cleaning and filtering protocols. This includes handling missing values, correcting discrepancies, and ensuring consistency across datasets. For example, we exclude patch-level images lacking valid 'Presence' annotations to prevent noise in training. Additionally, we address class imbalance by balancing the dataset concerning the number of images per patient and class. Balancing is critical as it prevents the model from becoming biased toward majority classes, ensuring equitable learning across all classes.
Data Exploration
Prior to model development, an in-depth data exploration phase is conducted to comprehend the intrinsic properties of the dataset. This encompasses assessing the distribution of classes within both patch-level and patient-level datasets. Understanding class distribution is vital, as significant imbalances can bias the model's learning process. Identifying such imbalances informs the decision to adjust loss functions by incorporating class weights or to employ resampling techniques, thereby enhancing model fairness and performance.
Visual examination of images is performed to gain qualitative insights into the data. By inspecting sample images from various classes, we can detect anomalies, artifacts, or patterns that may influence model learning. This step is crucial for identifying issues such as inconsistent staining in histopathological images or the presence of imaging artifacts, which may necessitate corrective preprocessing steps.
Statistical analyses are conducted to compute key metrics such as the number of images per patient, patches per class, and annotation distributions. These statistics inform data augmentation strategies and hyperparameter tuning. For instance, if certain classes are underrepresented, augmentation techniques like rotation or flipping can be applied to enrich the dataset. Hyperparameters such as learning rate, batch size, and the number of epochs can be adjusted based on dataset size and complexity to optimize model training.
Ensuring data integrity is a non-negotiable aspect of our workflow. We perform rigorous checks to verify that image filenames correctly map to their annotations. This verification prevents mislabeling, which could compromise the validity of the training process and lead to erroneous model predictions.
Model Selection and Training
Our modeling framework is designed with flexibility, offering the option to pursue either classification or detection approaches. This selection is facilitated through a user interface where the input '0' initiates classifier training, while '1' would commence training a detection model. Focusing on the classifier, our objective is to develop a model capable of accurately categorizing images based on provided annotations.
Data loading and transformation are executed using custom functions tailored to our dataset's structure. Images sourced from USABLE_annotated are preprocessed through a transformation pipeline that resizes images to a consistent dimension and converts them into tensors—the format required for input into neural networks. Standardizing image sizes ensures uniformity in computational workload and leverages the architecture of convolutional neural networks (CNNs), which are sensitive to input dimensions.
The dataset is encapsulated within a custom class, StandardImageDataset, which establishes a pairing between images and their corresponding labels extracted from TRAIN_DATA_annotated.csv. This encapsulation is essential for utilizing data loaders that handle batching and shuffling during training. Batching optimizes GPU utilization, while shuffling ensures that the model does not learn spurious correlations resulting from the order of data.
For the model architecture, we explore a range of configurations by experimenting with different deep learning models and hyperparameters. We employ pre-trained models such as ResNet50 and DenseNet201 as the foundational backbones. Leveraging these architectures is strategic because they have been pre-trained on large-scale datasets like ImageNet, enabling transfer learning. This approach benefits from the rich feature representations learned in these models, which can be fine-tuned for our specific classification task, thereby reducing training time and improving performance.
Custom fully connected layers are appended atop the backbone networks to adapt them to our classification problem. The depth and size of these layers are chosen based on the complexity of the task and the amount of training data available. A deeper network with more parameters may capture more intricate patterns but also requires more data to generalize well.
The loss function selected is cross-entropy loss, augmented with class weights to address any class imbalance identified during data exploration. Incorporating class weights penalizes the loss function more when misclassifying minority classes, thereby guiding the model to pay equal attention to all classes. The optimizer of choice is Adam, known for its adaptive learning rate capability, which enhances convergence speed and stability. Selecting an appropriate learning rate is crucial; too high may cause the model to diverge, while too low may result in prolonged training times and convergence to suboptimal minima.
Training involves iterating over the dataset for a defined number of epochs. In each iteration, the model processes batches of data, computes the loss, and updates the model weights through backpropagation. We diligently record metrics such as training loss, accuracy, and recall after each epoch. Monitoring these metrics is important for diagnosing issues like overfitting or underfitting and for determining the optimal stopping point for training.
Upon completion of training, we evaluate the model on a validation set to assess its generalization capabilities. Metrics such as validation loss, accuracy, precision, recall, and F1-score provide a comprehensive view of performance. Evaluating multiple metrics is important because accuracy alone may be misleading in imbalanced datasets.
The trained models are saved to disk to enable future inference or for use as a starting point in transfer learning for related tasks. Additionally, we generate plots of the training and validation metrics over epochs. Visualizing the training progression aids in understanding the learning dynamics and in communicating results to stakeholders.
By systematically experimenting with various architectures and hyperparameters and by justifying our choices based on data characteristics and theoretical considerations, we aim to identify the model configuration that achieves optimal performance. This iterative and analytically driven approach is essential for developing robust models capable of accurate and reliable predictions on complex datasets.