
Public Member Functions | |
| __init__ (self, int num_classes, int vocab_size, int embedding_dim=100, int word_hidden_dim=50, int sent_hidden_dim=50, str lsnet_model_size='s', float dropout=0.7, float learning_rate=0.0003, float weight_decay=0.05, Optional[str] device=None, int num_epochs=70, str save_dir="models/hybrid", int patience=15, bool mixed_precision=True, str scheduler_type="cosine", bool use_ocr_text=True, bool use_resnet=False, str resnet_model_name="resnet50", bool resnet_pretrained=True # Added parameter for pre-trained ResNet) | |
| train_model (self, train_loader, val_loader=None, tb_logger=None, **kwargs) | |
| evaluate (self, data_loader, tb_logger=None, step=None) | |
| inference (self, image, text) | |
| predict_proba (self, image, text) | |
| save (self, path=None) | |
| load (self, path, map_location=None) | |
Static Public Member Functions | |
| create_dataloader (dataframe, bucket_name, tokenizer=None, vocab=None, batch_size=32, shuffle=True, num_workers=4, max_sentences=15, max_sent_length=50, image_transform=None, batch_tokenize=True, **kwargs) | |
Protected Member Functions | |
| _process_batch (self, batch, batch_idx=None) | |
Trainer for the HybridClassifier model. This trainer handles training, evaluation, and inference for the hybrid model.
| hybrid.HybridTrainer.__init__ | ( | self, | |
| int | num_classes, | ||
| int | vocab_size, | ||
| int | embedding_dim = 100, |
||
| int | word_hidden_dim = 50, |
||
| int | sent_hidden_dim = 50, |
||
| str | lsnet_model_size = 's', |
||
| float | dropout = 0.7, |
||
| float | learning_rate = 0.0003, |
||
| float | weight_decay = 0.05, |
||
| Optional[str] | device = None, |
||
| int | num_epochs = 70, |
||
| str | save_dir = "models/hybrid", |
||
| int | patience = 15, |
||
| bool | mixed_precision = True, |
||
| str | scheduler_type = "cosine", |
||
| bool | use_ocr_text = True, |
||
| bool | use_resnet = False, |
||
| str | resnet_model_name = "resnet50", |
||
| bool | resnet_pretrained = True # Added parameter for pre-trained ResNet |
||
| ) |
Initialize the HybridTrainer.
Args:
num_classes: Number of document classes
vocab_size: Size of the vocabulary for text embedding
embedding_dim: Dimension of the word embeddings
word_hidden_dim: Dimension of the word-level GRU hidden state
sent_hidden_dim: Dimension of the sentence-level GRU hidden state
lsnet_model_size: LSNet model size ('t', 's', or 'b')
dropout: Dropout rate for regularization
learning_rate: Learning rate for the optimizer
weight_decay: Weight decay for the optimizer
device: Device to use for training (CPU or GPU)
num_epochs: Number of training epochs
save_dir: Directory to save model checkpoints
patience: Number of epochs to wait for improvement before early stopping
mixed_precision: Whether to use mixed precision training
scheduler_type: Type of learning rate scheduler to use ('cosine', 'onecycle', or 'plateau')
use_ocr_text: Whether to use OCR text from the dataset
use_resnet: Whether to use ResNet instead of LSNet
resnet_model_name: Name of the ResNet model to use
resnet_pretrained: Whether to use pre-trained ResNet weights
|
protected |
Process batches of different formats into standardized inputs.
Args:
batch: Batch from DataLoader
batch_idx: Optional batch index for debugging
Returns:
Tuple of (docs, images, labels) on device, or None if batch cannot be processed
|
static |
Create a DataLoader for the HybridModel using MinioMultiModalDataset.
Args:
dataframe: DataFrame with 'image' URL, 'label', and 'ocr_text' columns
bucket_name: MinIO bucket name
tokenizer: Tokenizer for text processing
vocab: Vocabulary for text processing
batch_size: Batch size for the DataLoader
shuffle: Whether to shuffle the data
num_workers: Number of worker processes for the DataLoader
max_sentences: Maximum number of sentences to keep from OCR text
max_sent_length: Maximum number of tokens per sentence
image_transform: Transformations for the images
batch_tokenize: Whether to tokenize in batches (more efficient)
**kwargs: Additional arguments for MinioMultiModalDataset
Returns:
DataLoader for the HybridModel
| hybrid.HybridTrainer.evaluate | ( | self, | |
| data_loader, | |||
tb_logger = None, |
|||
step = None |
|||
| ) |
Evaluate the hybrid model on a dataset.
Args:
data_loader: DataLoader for evaluation data
tb_logger: Optional TensorBoard logger
step: Current step (epoch) for logging
Returns:
Tuple of (accuracy, loss)
| hybrid.HybridTrainer.inference | ( | self, | |
| image, | |||
| text | |||
| ) |
Perform inference with the hybrid model.
Args:
image: Input image (PIL.Image, numpy array, or tensor)
text: Input text as processed and tokenized tensor
Returns:
Predicted class index
| hybrid.HybridTrainer.load | ( | self, | |
| path, | |||
map_location = None |
|||
| ) |
Load a model from a file.
Args:
path: Path to load the model from
map_location: Device to map the model to (default: self.device)
| hybrid.HybridTrainer.predict_proba | ( | self, | |
| image, | |||
| text | |||
| ) |
Get class probabilities for the input.
Args:
image: Input image (PIL.Image, numpy array, or tensor)
text: Input text as processed and tokenized tensor
Returns:
Class probabilities as numpy array
| hybrid.HybridTrainer.save | ( | self, | |
path = None |
|||
| ) |
Save the model to a file.
Args:
path: Path to save the model (default: best_model.pth in save_dir)
| hybrid.HybridTrainer.train_model | ( | self, | |
| train_loader, | |||
val_loader = None, |
|||
tb_logger = None, |
|||
| ** | kwargs | ||
| ) |
Train the hybrid model.
Args:
train_loader: DataLoader for training data
val_loader: Optional DataLoader for validation data
tb_logger: Optional TensorBoard logger
**kwargs: Additional arguments
Returns:
Best validation accuracy
| hybrid.HybridTrainer.classifier |
| hybrid.HybridTrainer.device |
| hybrid.HybridTrainer.dropout |
| hybrid.HybridTrainer.embedding_dim |
| hybrid.HybridTrainer.learning_rate |
| hybrid.HybridTrainer.lsnet_model_size |
| hybrid.HybridTrainer.mixed_precision |
| hybrid.HybridTrainer.num_classes |
| hybrid.HybridTrainer.num_epochs |
| hybrid.HybridTrainer.patience |
| hybrid.HybridTrainer.resnet_model_name |
| hybrid.HybridTrainer.resnet_pretrained |
| hybrid.HybridTrainer.save_dir |
| hybrid.HybridTrainer.scaler |
| hybrid.HybridTrainer.scheduler_type |
| hybrid.HybridTrainer.sent_hidden_dim |
| hybrid.HybridTrainer.use_ocr_text |
| hybrid.HybridTrainer.use_resnet |
| hybrid.HybridTrainer.vocab_size |
| hybrid.HybridTrainer.weight_decay |
| hybrid.HybridTrainer.word_hidden_dim |