<jupyter_start><jupyter_text>Advanced usage This notebook shows some more advanced features of `skorch`. More examples will be added with time.    Run in Google Colab  View source on GitHub  Table of contents * [Setup](Setup)* [Callbacks](Callbacks)  * [Writing your own callback](Writing-a-custom-callback)  * [Accessing callback parameters](Accessing-callback-parameters)* [Working with different data types](Working-with-different-data-types)  * [Working with datasets](Working-with-Datasets)  * [Working with dicts](Working-with-dicts)<jupyter_code>! [ ! -z "$COLAB_GPU" ] && pip install torch skorch
import torch
from torch import nn
import torch.nn.functional as F
torch.manual_seed(0);<jupyter_output><empty_output><jupyter_text>Setup  A toy binary classification task We load a toy classification task from `sklearn`.<jupyter_code>import numpy as np
from sklearn.datasets import make_classification
X, y = make_classification(1000, 20, n_informative=10, random_state=0)
X = X.astype(np.float32)
X.shape, y.shape, y.mean()<jupyter_output><empty_output><jupyter_text>Definition of the `pytorch` classification `module` We define a vanilla neural network with two hidden layers. The output layer should have 2 output units since there are two classes. In addition, it should have a softmax nonlinearity, because later, when calling `predict_proba`, the output from the `forward` call will be used.<jupyter_code>from skorch import NeuralNetClassifier
class ClassifierModule(nn.Module):
    def __init__(
            self,
            num_units=10,
            nonlin=F.relu,
            dropout=0.5,
    ):
        super(ClassifierModule, self).__init__()
        self.num_units = num_units
        self.nonlin = nonlin
        self.dropout = dropout

        self.dense0 = nn.Linear(20, num_units)
        self.nonlin = nonlin
        self.dropout = nn.Dropout(dropout)
        self.dense1 = nn.Linear(num_units, 10)
        self.output = nn.Linear(10, 2)

    def forward(self, X, **kwargs):
        X = self.nonlin(self.dense0(X))
        X = self.dropout(X)
        X = F.relu(self.dense1(X))
        X = F.softmax(self.output(X), dim=-1)
        return X<jupyter_output><empty_output><jupyter_text>Callbacks Callbacks are a powerful and flexible way to customize the behavior of your neural network. They are all called at specific points during the model training, e.g. when training starts, or after each batch. Have a look at the `skorch.callbacks` module to see the callbacks that are already implemented.  Writing a custom callback Although `skorch` comes with a handful of useful callbacks, you may find that you would like to write your own callbacks. Doing so is straightforward, just remember these rules:* They should inherit from `skorch.callbacks.Callback`.* They should implement at least one of the `on_`-methods provided by the parent class (e.g. `on_batch_begin` or `on_epoch_end`).* As argument, the `on_`-methods first get the `NeuralNet` instance, and, where appropriate, the local data (e.g. the data from the current batch). The method should also have `**kwargs` in the signature for potentially unused arguments.* *Optional*: If you have attributes that should be reset when the model is re-initialized, those attributes should be set in the `initialize` method. Here is an example of a callback that remembers at which epoch the validation accuracy reached a certain value. Then, when training is finished, it calls a mock Twitter API and tweets that epoch. We proceed as follows:* We set the desired minimum accuracy during `__init__`.* We set the critical epoch during `initialize`.* After each epoch, if the critical accuracy has not yet been reached, we check if it was reached.* When training finishes, we send a tweet informing us whether our training was successful or not.<jupyter_code>from skorch.callbacks import Callback


def tweet(msg):
    print("~" * 60)
    print("*tweet*", msg, "#skorch #pytorch")
    print("~" * 60)


class AccuracyTweet(Callback):
    def __init__(self, min_accuracy):
        self.min_accuracy = min_accuracy

    def initialize(self):
        self.critical_epoch_ = -1

    def on_epoch_end(self, net, **kwargs):
        if self.critical_epoch_ > -1:
            return
        # look at the validation accuracy of the last epoch
        if net.history[-1, 'valid_acc'] >= self.min_accuracy:
            self.critical_epoch_ = len(net.history)

    def on_train_end(self, net, **kwargs):
        if self.critical_epoch_ < 0:
            msg = "Accuracy never reached {} :(".format(self.min_accuracy)
        else:
            msg = "Accuracy reached {} at epoch {}!!!".format(
                self.min_accuracy, self.critical_epoch_)

        tweet(msg)<jupyter_output><empty_output><jupyter_text>Now we initialize a `NeuralNetClassifier` and pass your new callback in a list to the `callbacks` argument. After that, we train the model and see what happens.<jupyter_code>net = NeuralNetClassifier(
    ClassifierModule,
    max_epochs=10,
    lr=0.02,
    warm_start=True,
    callbacks=[AccuracyTweet(min_accuracy=0.7)],
)
net.fit(X, y)<jupyter_output>epoch    train_loss    valid_acc    valid_loss     dur
-------  ------------  -----------  ------------  ------
      1        [36m0.6954[0m       [32m0.6000[0m        [35m0.6844[0m  0.0561
      2        [36m0.6802[0m       0.5950        [35m0.6817[0m  0.0182
      3        0.6839       0.6000        [35m0.6792[0m  0.0182
      4        [36m0.6753[0m       0.5900        [35m0.6767[0m  0.0189
      5        0.6769       0.5950        [35m0.6742[0m  0.0184
      6        0.6774       [32m0.6050[0m        [35m0.6720[0m  0.0176
      7        [36m0.6693[0m       [32m0.6250[0m        [35m0.6695[0m  0.0183
      8        0.6694       [32m0.6300[0m        [35m0.6672[0m  0.0180
      9        0.6703       [32m0.6400[0m        [35m0.6652[0m  0.0192
     10        [36m0.6523[0m       [32m0.6550[0m        [35m0.6623[0m  0.0189
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*tweet* Accuracy never reached 0.7 :( #skorch #pytorch
~~~~~~~~~~~[...]<jupyter_text>Oh no, our model never reached a validation accuracy of 0.7. Let's train some more (this is possible because we set `warm_start=True`):<jupyter_code>net.fit(X, y)<jupyter_output>11        0.6641       [32m0.6650[0m        [35m0.6603[0m  0.0176
     12        0.6524       0.6650        [35m0.6582[0m  0.0196
     13        [36m0.6506[0m       [32m0.6700[0m        [35m0.6553[0m  0.0184
     14        [36m0.6489[0m       0.6650        [35m0.6527[0m  0.0192
     15        0.6505       [32m0.6750[0m        [35m0.6502[0m  0.0175
     16        [36m0.6473[0m       0.6750        [35m0.6474[0m  0.0185
     17        [36m0.6431[0m       [32m0.6800[0m        [35m0.6443[0m  0.0171
     18        0.6461       [32m0.6900[0m        [35m0.6418[0m  0.0182
     19        [36m0.6430[0m       0.6850        [35m0.6392[0m  0.0200
     20        [36m0.6364[0m       [32m0.6950[0m        [35m0.6366[0m  0.0187
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*tweet* Accuracy never reached 0.7 :( #skorch #pytorch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<jupyter_text>Finally, the validation score exceeded 0.7. Hooray!  Accessing callback parameters Say you would like to use a learning rate schedule with your neural net, but you don't know what parameters are best for that schedule. Wouldn't it be nice if you could find those parameters with a grid search? With `skorch`, this is possible. Below, we show how to access the parameters of your callbacks. To simplify the access to your callback parameters, it is best if you give your callback a name. This is achieved by passing the `callbacks` parameter a list of *name*, *callback* tuples, such as:    callbacks=[        ('scheduler', LearningRateScheduler)),        ...    ],    This way, you can access your callbacks using the double underscore semantics (as, for instance, in an `sklearn` `Pipeline`):    callbacks__scheduler__epoch=50,So if you would like to perform a grid search on, say, the number of units in the hidden layer and the learning rate schedule, it could look something like this:    param_grid = {        'module__num_units': [50, 100, 150],        'callbacks__scheduler__epoch': [10, 50, 100],    }    *Note*: If you would like to refresh your knowledge on grid search, look [here](http://scikit-learn.org/stable/modules/grid_search.htmlgrid-search), [here](http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_text_feature_extraction.html), or in the *Basic_Usage* notebok. Below, we show how accessing the callback parameters works our `AccuracyTweet` callback:<jupyter_code>net = NeuralNetClassifier(
    ClassifierModule,
    max_epochs=10,
    lr=0.1,
    warm_start=True,
    callbacks=[
        ('tweet', AccuracyTweet(min_accuracy=0.7)),
    ],
    callbacks__tweet__min_accuracy=0.6,
)
net.fit(X, y)<jupyter_output>epoch    train_loss    valid_acc    valid_loss     dur
-------  ------------  -----------  ------------  ------
      1        [36m0.7114[0m       [32m0.5150[0m        [35m0.6923[0m  0.0180
      2        [36m0.6959[0m       [32m0.5300[0m        [35m0.6831[0m  0.0189
      3        [36m0.6856[0m       [32m0.6000[0m        [35m0.6752[0m  0.0181
      4        [36m0.6768[0m       [32m0.6300[0m        [35m0.6686[0m  0.0199
      5        [36m0.6670[0m       [32m0.6500[0m        [35m0.6585[0m  0.0173
      6        [36m0.6607[0m       0.6300        [35m0.6496[0m  0.0185
      7        [36m0.6375[0m       [32m0.6650[0m        [35m0.6377[0m  0.0193
      8        [36m0.6333[0m       [32m0.6800[0m        [35m0.6263[0m  0.0178
      9        [36m0.6160[0m       [32m0.6850[0m        [35m0.6117[0m  0.0187
     10        [36m0.6109[0m       0.6850        [35m0.5983[0m  0.0176
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*tw[...]<jupyter_text>As you can see, by passing `callbacks__tweet__min_accuracy=0.6`, we changed that parameter. The same can be achieved by calling the `set_params` method with the corresponding arguments:<jupyter_code>net.set_params(callbacks__tweet__min_accuracy=0.75)
net.fit(X, y)<jupyter_output>epoch    train_loss    valid_acc    valid_loss     dur
-------  ------------  -----------  ------------  ------
     11        [36m0.5926[0m       [32m0.6900[0m        [35m0.5844[0m  0.0206
     12        [36m0.5778[0m       [32m0.7000[0m        [35m0.5719[0m  0.0210
     13        0.5824       [32m0.7300[0m        [35m0.5597[0m  0.0198
     14        [36m0.5639[0m       [32m0.7350[0m        [35m0.5541[0m  0.0177
     15        [36m0.5580[0m       [32m0.7400[0m        [35m0.5451[0m  0.0187
     16        [36m0.5415[0m       [32m0.7500[0m        [35m0.5334[0m  0.0183
     17        0.5508       [32m0.7550[0m        [35m0.5333[0m  0.0190
     18        [36m0.5317[0m       0.7400        0.5338  0.0174
     19        [36m0.5209[0m       0.7400        [35m0.5225[0m  0.0187
     20        0.5275       0.7350        0.5227  0.0182
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*tweet* Accuracy reached 0.75 at epoch 16!!! #skorch #pyt[...]<jupyter_text>Working with different data types  Working with `Dataset`s We encourage you to not pass `Dataset`s to `net.fit` but to let skorch handle `Dataset`s internally. Nonetheless, there are situations where passing `Dataset`s to `net.fit` is hard to avoid (e.g. if you want to load the data lazily during the training). This is supported by skorch but may have some unwanted side-effects relating to sklearn. For instance, `Dataset`s cannot split into train and validation in a stratified fashion without explicit knowledge of the classification targets. Below we show what happens when you try to fit with `Dataset` and the stratified split fails:<jupyter_code>class MyDataset(torch.utils.data.Dataset):
    def __init__(self, X, y):
        self.X = X
        self.y = y
        
        assert len(X) == len(y)

    def __len__(self):
        return len(self.X)

    def __getitem__(self, i):
        return self.X[i], self.y[i]
X, y = make_classification(1000, 20, n_informative=10, random_state=0)
X = X.astype(np.float32)
dataset = MyDataset(X, y)
net = NeuralNetClassifier(ClassifierModule)
try:
    net.fit(dataset, y=None)
except ValueError as e:
    print("Error:", e)
net.train_split.stratified<jupyter_output><empty_output><jupyter_text>As you can see, the stratified split fails since `y` is not known. There are two solutions to this:* turn off stratified splitting ( `net.train_split.stratified=False`) * pass `y` explicitly (if possible), even if it is implicitely contained in the `Dataset`The second solution is shown below:<jupyter_code>net.fit(dataset, y=y)<jupyter_output>Re-initializing module!
  epoch    train_loss    valid_acc    valid_loss     dur
-------  ------------  -----------  ------------  ------
      1        [36m0.7869[0m       [32m0.5000[0m        [35m0.7649[0m  0.0164
      2        [36m0.7700[0m       0.5000        [35m0.7526[0m  0.0170
      3        [36m0.7594[0m       0.5000        [35m0.7424[0m  0.0172
      4        [36m0.7443[0m       0.5000        [35m0.7336[0m  0.0188
      5        [36m0.7388[0m       0.5000        [35m0.7261[0m  0.0159
      6        [36m0.7265[0m       0.5000        [35m0.7201[0m  0.0170
      7        [36m0.7229[0m       0.5000        [35m0.7148[0m  0.0155
      8        [36m0.7103[0m       0.5000        [35m0.7105[0m  0.0165
      9        [36m0.7095[0m       0.5000        [35m0.7067[0m  0.0166
     10        [36m0.7053[0m       0.5000        [35m0.7035[0m  0.0166<jupyter_text>Working with dicts  The standard case skorch has built-in support for dictionaries as data containers. Here we show a somewhat contrived example of how to use dicts, but it should get the point across. First we create data and put it into a dictionary `X_dict` with two keys `X0` and `X1`:<jupyter_code>X, y = make_classification(1000, 20, n_informative=10, random_state=0)
X0, X1 = X[:, :10].astype(np.float32), X[:, 10:].astype(np.float32)
X_dict = {'X0': X0, 'X1': X1}<jupyter_output><empty_output><jupyter_text>When skorch passes the dict to the pytorch module, it will pass the data as keyword arguments to the forward call. That means that we should accept the two keys `XO` and `X1` in the forward method, as shown below:<jupyter_code>class ClassifierWithDict(nn.Module):
    def __init__(
            self,
            num_units0=50,
            num_units1=50,
            nonlin=F.relu,
            dropout=0.5,
    ):
        super(ClassifierWithDict, self).__init__()
        self.num_units0 = num_units0
        self.num_units1 = num_units1
        self.nonlin = nonlin
        self.dropout = dropout

        self.dense0 = nn.Linear(10, num_units0)
        self.dense1 = nn.Linear(10, num_units1)
        self.nonlin = nonlin
        self.dropout = nn.Dropout(dropout)
        self.output = nn.Linear(num_units0 + num_units1, 2)

    # NOTE: We accept X0 and X1, the keys from the dict, as arguments
    def forward(self, X0, X1, **kwargs):
        X0 = self.nonlin(self.dense0(X0))
        X0 = self.dropout(X0)

        X1 = self.nonlin(self.dense1(X1))
        X1 = self.dropout(X1)

        X = torch.cat((X0, X1), dim=1)
        X = F.relu(X)
        X = F.softmax(self.output(X), dim=-1)
        return X<jupyter_output><empty_output><jupyter_text>As long as we keep this in mind, we are good to go.<jupyter_code>net = NeuralNetClassifier(ClassifierWithDict, verbose=0)
net.fit(X_dict, y)<jupyter_output><empty_output><jupyter_text>Working with sklearn `FunctionTransformer` and `GridSearch`<jupyter_code>from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer
from sklearn.model_selection import GridSearchCV<jupyter_output><empty_output><jupyter_text>sklearn makes the assumption that incoming data should be numpy/sparse arrays or something similar. This clashes with the use of dictionaries. Unfortunately, it is sometimes impossible to work around that for now (for instance using skorch with `BaggingClassifier`). Other times, there are possibilities.When we have a preprocessing pipeline that involves `FunctionTransformer`, we have to pass the parameter `validate=False` so that sklearn allows the dictionary to pass through:<jupyter_code>pipe = Pipeline([
    ('do-nothing', FunctionTransformer(validate=False)),
    ('net', net),
])
pipe.fit(X_dict, y)<jupyter_output><empty_output><jupyter_text>When trying a grid or randomized search, it is not that easy to pass a dict. If we try, we will get an error:<jupyter_code>param_grid = {
    'net__module__num_units0': [10, 25, 50], 
    'net__module__num_units1': [10, 25, 50],
    'net__lr': [0.01, 0.1],
}
grid_search = GridSearchCV(pipe, param_grid, scoring='accuracy', verbose=1, cv=3)
try:
    grid_search.fit(X_dict, y)
except Exception as e:
    print(e)<jupyter_output>Found input variables with inconsistent numbers of samples: [2, 1000]<jupyter_text>The error above occurs because sklearn gets the length of the input data, which is 2 for the dict, and believes that is inconsistent with the length of the target (1000). To get around that, skorch provides a helper class called `SliceDict`. It allows us to wrap our dictionaries so that they also behave like a numpy array:<jupyter_code>from skorch.helper import SliceDict
X_slice_dict = SliceDict(X0=X0, X1=X1)  # X_slice_dict = SliceDict(**X_dict) would also work<jupyter_output><empty_output><jupyter_text>The SliceDict shows the correct length, shape, and is sliceable across values:<jupyter_code>print("Length of dict: {}, length of SliceDict: {}".format(len(X_dict), len(X_slice_dict)))
print("Shape of SliceDict: {}".format(X_slice_dict.shape))
print("Slicing the SliceDict slices across values: {}".format(X_slice_dict[:2]))<jupyter_output>Slicing the SliceDict slices across values: SliceDict(**{'X0': array([[-0.9658346 , -2.1890705 ,  0.16985609,  0.8138456 , -3.375209  ,
        -2.1430597 , -0.39585084,  2.9419577 , -2.1910605 ,  1.2443967 ],
       [-0.454767  ,  4.339768  , -0.48572844, -4.88433   , -2.8836503 ,
         2.6097205 , -1.952876  , -0.09192174,  0.07970932, -0.08938338]],
      dtype=float32), 'X1': array([[ 0.04351204, -0.5150961 , -0.86073655, -1.1097169 ,  0.31839254,
        -0.8231973 , -1.056304  , -0.89645284,  0.3759244 , -1.0849651 ],
       [-0.60726726, -1.0674309 ,  0.48804346, -0.50230557,  0.55743027,
         1.01592   , -1.9953582 ,  2.9030426 , -0.9739298 ,  2.1753323 ]],
      dtype=float32)})<jupyter_text>With this, we can call `GridSearch` just as expected:<jupyter_code>grid_search.fit(X_slice_dict, y)
grid_search.best_score_, grid_search.best_params_<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1361046634311036, 'fraction_numerical': 0.10276429626503482, 'mean_word_length': 2.8942070665571076, 'pattern_counts': {'":': 0, '<': 71, '<?xml version=': 0, '>': 72, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '313091', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 7583, 'n_tokens_neox': 6454, 'n_words': 1773, 'path': 'notebooks/Advanced_Usage.ipynb', 'repo_name': 'damienlancry/skorch', 'size': '18956'}