skorch Documentation

repository·master·Indexed 27 days ago

https://github.com/skorch-dev/skorch

A scikit-learn compatible neural network library that wraps PyTorch. skorch provides an sklearn-style interface for PyTorch models, allowing developers to use PyTorch within standard scikit-learn workflows such as Pipelines and Grid Search. It abstracts the training loop and supports PyTorch Tensors, NumPy arrays, and Python dictionaries.

Tokens
36.3K
Snippets
88
Records
199
Agent score
91%

What's inside skorch

  1. Overview of skorch

    master

    skorch is a scikit-learn compatible neural network library that wraps PyTorch. It provides an sklearn-style interface for PyTorch models, allowing you to use familiar syntax like net.fit(X, y) to handle the training loop and boilerplate code.

    Key features include:

    • sklearn compatibility: Use PyTorch models within scikit-learn workflows.
    • Boilerplate reduction: Abstracts away the training loop.
    • Data flexibility: Works out-of-the-box with PyTorch Tensors, NumPy arrays, Python dicts, and more.
    • Extensibility: Easy to extend for custom data types.
  2. Advantages of using skorch for LLM classification

    master

    Using skorch.llm.classifier.ZeroShotClassifier and skorch.llm.classifier.FewShotClassifier provides several benefits for machine learning workflows:

    • Label Constraint: Ensures the LLM only predicts from a predefined list of labels by intercepting logits, preventing undesired text outputs.
    • Probability Estimation: Provides a .predict_proba method that returns class probabilities by inspecting model logits rather than just returning generated text.
    • Scikit-learn Compatibility: Classifiers follow the sklearn API (fit, predict, predict_proba), allowing them to be used in grid searches or as drop-in replacements for existing models.
    • Local Execution: Once models and tokenizers are downloaded, all processing happens locally. No data is sent to external APIs (like OpenAI), ensuring data privacy.
    • Caching: Internal caching improves prediction speed, particularly for long labels with common prefixes.
  3. Support for Large Language Models (LLMs)

    master
    While skorch is primarily designed for training models from scratch, it provides integrations with the Hugging Face ecosystem. This allows users to leverage pre-trained Large Language Models (LLMs) from Hugging Face within skorch workflows. Common use cases include using LLMs as zero-shot or few-shot classifiers.
  4. Available skorch features and callbacks

    master

    skorch provides several advanced features and callbacks to enhance training workflows:

    • Learning rate schedulers: Support for Warm restarts, cyclic LR, etc. (skorch.callbacks.LRScheduler)
    • Scoring: Use sklearn (and custom) scoring functions via skorch.callbacks.EpochScoring
    • Early stopping: via skorch.callbacks.EarlyStopping
    • Checkpointing: via skorch.callbacks.Checkpoint
    • Parameter freezing/unfreezing: via skorch.callbacks.Freezer
    • Progress bar: Support for CLI and Jupyter via skorch.callbacks.ProgressBar
    • CLI Integration: Automatic inference of CLI parameters
    • GPyTorch Integration: For Gaussian Processes
    • Hugging Face Integration: Support for 🤗 models
  5. Explore skorch usage through Jupyter Notebooks

    master

    You can learn how to use skorch through a collection of hosted Jupyter Notebooks covering various complexity levels and use cases. These notebooks provide practical examples for basic setup, advanced configurations, and specific deep learning tasks.

    ### Available Notebook Examples:
    
    * [Basic usage](https://nbviewer.jupyter.org/github/skorch-dev/skorch/blob/master/notebooks/Basic_Usage.ipynb)
    * [Advanced usage](https://nbviewer.jupyter.org/github/skorch-dev/skorch/blob/master/notebooks/Advanced_Usage.ipynb)
    * [MNIST](https://nbviewer.jupyter.org/github/skorch-dev/skorch/blob/master/notebooks/MNIST.ipynb)
    * [MNIST using torchvision](https://nbviewer.jupyter.org/github/skorch-dev/skorch/blob/master/notebooks/MNIST-torchvision.ipynb)
    * [Transfer Learning](https://nbviewer.jupyter.org/github/skorch-dev/skorch/blob/master/notebooks/Transfer_Learning.ipynb)
    * [Gaussian Processes](https://nbviewer.jupyter.org/github/skorch-dev/skorch/blob/master/notebooks/Gaussian_Processes.ipynb)
    * [PyTorch Geometric on the CORA dataset](https://nbviewer.jupyter.org/github/skorch-dev/skorch/blob/master/notebooks/CORA-geometric.ipynb)
    * [Hugging Face fine-tuning](https://nbviewer.org/github/skorch-dev/skorch/blob/master/notebooks/Hugging_Face_Finetuning.ipynb)
    * [Hugging Face Hub Checkpoints](https://nbviewer.org/github/skorch-dev/skorch/blob/master/notebooks/Hugging_Face_Model_Checkpoint.ipynb)
    * [Hugging Face Vision Transformer](https://nbviewer.org/github/skorch-dev/skorch/blob/master/notebooks/Hugging_Face_VisionTransformer.ipynb)
    * [Skorch Doctor](https://nbviewer.org/github/skorch-dev/skorch/blob/master/notebooks/Skorch_Doctor.ipynb)
    * [Classification with LLMs](https://nbviewer.org/github/skorch-dev/skorch/blob/master/notebooks/LLM_Classifier.ipynb)
    * [Learning Rate Scheduler](https://nbviewer.org/github/skorch-dev/skorch/blob/master/notebooks/Learning_Rate_Scheduler.ipynb)
    * [Streaming Dataset](https://nbviewer.org/github/skorch-dev/skorch/blob/master/notebooks/Streaming_Dataset.ipynb)
  6. Use callbacks for saving and loading models

    master

    skorch provides several callbacks to manage model checkpoints during training:

    • Checkpoint: Saves the model parameters, optimizer, and history. By default, it monitors valid_loss and saves the model whenever this metric improves.
    • TrainEndCheckpoint: Creates a checkpoint specifically at the end of the training procedure.
    • LoadInitState: Initializes the model, history, and optimizer parameters from a specified checkpoint at the beginning of training. This is useful for resuming training (e.g., with a different learning rate) or continuing from a previous experiment.

    To use them, include them in the callbacks list when initializing your NeuralNet class.

    from skorch.callbacks import Checkpoint, TrainEndCheckpoint, LoadInitState
    from skorch import NeuralNetClassifier
    
    # To save checkpoints during training
    cp = Checkpoint(dirname='exp1')
    train_end_cp = TrainEndCheckpoint(dirname='exp1')
    
    # To resume training from a checkpoint
    load_state = LoadInitState(cp)
    
    net = NeuralNetClassifier(
        MyModule, 
        lr=0.1, 
        callbacks=[cp, load_state]
    )
    
    net.fit(X, y)
  7. Use sample weights in skorch

    master

    To use sample_weight, pass it as part of a dictionary for X. This ensures weights are correctly split into train/valid sets and batched. You must also:

    1. Ensure your forward method accepts the weight argument.
    2. Set criterion__reduce=False so the loss is not reduced before weighting.
    3. Override get_loss to apply the weights to the unreduced loss.
        X, y = get_data()
        # put your X into a dict if not already a dict
        X = {'data': X}
        # add sample_weight to the X dict
        X['sample_weight'] = sample_weight
    
        class MyModule(nn.Module):
            ...
            def forward(self, data, sample_weight):
                # when X is a dict, its keys are passed as kwargs to forward;
                # usually, sample_weight can be ignored here
                ...
    
        class MyNet(NeuralNet):
            def __init__(self, *args, criterion__reduce=False, **kwargs):
                # make sure to set reduce=False in your criterion, since we need the loss
                # for each sample so that it can be weighted
                super().__init__(*args, criterion__reduce=criterion__reduce, **kwargs)
    
            def get_loss(self, y_pred, y_true, X, *args, **kwargs):
                # override get_loss to use the sample_weight from X
                loss_unreduced = super().get_loss(y_pred, y_true, X, *args, **kwargs)
                sample_weight = skorch.utils.to_tensor(X['sample_weight'], device=self.device)
                loss_reduced = (sample_weight * loss_unreduced).mean()
                return loss_reduced
    
        net = MyNet(MyModule, ...)
        net.fit(X, y)
  8. Behavior of NeuralNet with initialized PyTorch modules

    master

    When passing an already initialized PyTorch module to NeuralNet:

    • If you pass the module instance directly, skorch leaves it alone. Subsequent calls to fit on the same instance will continue training from the current parameters.
    • If you pass module parameters via keyword arguments (e.g., module__hidden=10), skorch will re-initialize the module.
    • Recommendation: Pass the module class instead of an instance. This ensures fit always re-initializes the model, providing more predictable behavior.