DAPPER (Document Analysis, Processing, and Pattern Extraction Repository)
Statistical Learning Final Project for Document Classification
 
Loading...
Searching...
No Matches
hybrid.HybridTrainer Class Reference
Collaboration diagram for hybrid.HybridTrainer:
Collaboration graph

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)
 

Public Attributes

 num_classes
 
 vocab_size
 
 embedding_dim
 
 word_hidden_dim
 
 sent_hidden_dim
 
 lsnet_model_size
 
 dropout
 
 learning_rate
 
 weight_decay
 
 num_epochs
 
 save_dir
 
 patience
 
 mixed_precision
 
 scheduler_type
 
 use_ocr_text
 
 use_resnet
 
 resnet_model_name
 
 resnet_pretrained
 
 device
 
 classifier
 
 scaler
 

Protected Member Functions

 _process_batch (self, batch, batch_idx=None)
 

Detailed Description

Trainer for the HybridClassifier model.
This trainer handles training, evaluation, and inference for the hybrid model.

Constructor & Destructor Documentation

◆ __init__()

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

Member Function Documentation

◆ _process_batch()

hybrid.HybridTrainer._process_batch (   self,
  batch,
  batch_idx = None 
)
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

◆ create_dataloader()

hybrid.HybridTrainer.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 
)
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

◆ evaluate()

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)

◆ inference()

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

◆ load()

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)

◆ predict_proba()

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

◆ save()

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)

◆ train_model()

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

Member Data Documentation

◆ classifier

hybrid.HybridTrainer.classifier

◆ device

hybrid.HybridTrainer.device

◆ dropout

hybrid.HybridTrainer.dropout

◆ embedding_dim

hybrid.HybridTrainer.embedding_dim

◆ learning_rate

hybrid.HybridTrainer.learning_rate

◆ lsnet_model_size

hybrid.HybridTrainer.lsnet_model_size

◆ mixed_precision

hybrid.HybridTrainer.mixed_precision

◆ num_classes

hybrid.HybridTrainer.num_classes

◆ num_epochs

hybrid.HybridTrainer.num_epochs

◆ patience

hybrid.HybridTrainer.patience

◆ resnet_model_name

hybrid.HybridTrainer.resnet_model_name

◆ resnet_pretrained

hybrid.HybridTrainer.resnet_pretrained

◆ save_dir

hybrid.HybridTrainer.save_dir

◆ scaler

hybrid.HybridTrainer.scaler

◆ scheduler_type

hybrid.HybridTrainer.scheduler_type

◆ sent_hidden_dim

hybrid.HybridTrainer.sent_hidden_dim

◆ use_ocr_text

hybrid.HybridTrainer.use_ocr_text

◆ use_resnet

hybrid.HybridTrainer.use_resnet

◆ vocab_size

hybrid.HybridTrainer.vocab_size

◆ weight_decay

hybrid.HybridTrainer.weight_decay

◆ word_hidden_dim

hybrid.HybridTrainer.word_hidden_dim

The documentation for this class was generated from the following file: