Commit de6d31c0 authored by peastman's avatar peastman
Browse files

Fixed example in tutorial

parent f6877ba1
Loading
Loading
Loading
Loading
+1 −5
Original line number Diff line number Diff line
@@ -36,14 +36,10 @@ from deepchem.feat.material_featurizers import SineCoulombMatrix
from deepchem.feat.material_featurizers import CGCNNFeaturizer

try:
  from logging import getLogger
  logger = getLogger(__name__)
  import transformers
  from transformers import BertTokenizer

  from deepchem.feat.smiles_tokenizer import SmilesTokenizer
  from deepchem.feat.smiles_tokenizer import BasicSmilesTokenizer
except ModuleNotFoundError:
  logger.warning(
      "HuggingFace transformers is not available. Please install using 'pip install transformers' to use the SmilesTokenizer"
  )
  pass
+1 −8
Original line number Diff line number Diff line
@@ -14,13 +14,6 @@ from transformers import BertTokenizer
from logging import getLogger

logger = getLogger(__name__)

try:
  from transformers import BertTokenizer
except ModuleNotFoundError:
  logger.warning(
      "HuggingFace transformers is not available. Please install using 'pip install transformers' to use the SmilesTokenizer"
  )
"""
SMI_REGEX_PATTERN: str
    SMILES regex pattern for tokenization. Designed by Schwaller et. al.
+11 −11
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

# Tutorial Part ??: Creating Models with TensorFlow and PyTorch

In the tutorials so far, we have used standard models provided by DeepChem.  This is fine for many applications, but sooner or later you will want to create an entirely new model with an architecture you define yourself.  DeepChem provides integration with both TensorFlow (Keras) and PyTorch, so you can use it with models from either of these frameworks.

Actually, there are two different approaches you can take to this.  It depends on whether you want to use TensorFlow/PyTorch APIs or DeepChem APIs for training and evaluating your model.  For the former case, DeepChem's `Dataset` class has methods for easily adapting it to use with other frameworks.  `make_tf_dataset()` returns a `tensorflow.data.Dataset` object that iterates over the data.  `make_pytorch_dataset()` returns a `torch.utils.data.IterableDataset` that iterates over the data.  This lets you use DeepChem's datasets, loaders, featurizers, transformers, splitters, etc. and easily integrate them into your existing TensorFlow or PyTorch code.

But DeepChem also provides many other useful features.  The other approach, which lets you use those features, is to wrap your model in a DeepChem `Model` object.  Let's look at how to do that.

## KerasModel

`KerasModel` is a subclass of DeepChem's `Model` class.  It acts as a wrapper around a `tensorflow.keras.Model`.  Let's see an example of using it.  For this example, we create a simple sequential model consisting of two dense layers.

%% Cell type:code id: tags:

``` python
import deepchem as dc
import tensorflow as tf

keras_model = tf.keras.Sequential([
    tf.keras.layers.Dense(1000, activation='relu'),
    tf.keras.layers.Dropout(rate=0.5),
    tf.keras.layers.Dense(1)
])
model = dc.models.KerasModel(keras_model, dc.models.losses.L2Loss())
```

%% Cell type:markdown id: tags:

For this example, we used the Keras `Sequential` class.  Our model consists of a dense layer with ReLU activation, 50% dropout to provide regularization, and a final layer that produces a scalar output.  We also need to specify the loss function to use when training the model, in this case L<sub>2</sub> loss.  We can now train and evaluate the model exactly as we would with any other DeepChem model.  For example, let's load the Delaney solubility dataset.  How does our model do at predicting the solubilities of molecules based on their extended-connectivity fingerprints (ECFPs)?

%% Cell type:code id: tags:

``` python
tasks, datasets, transformers = dc.molnet.load_delaney(featurizer='ECFP', splitter='random')
train_dataset, valid_dataset, test_dataset = datasets
model.fit(train_dataset, nb_epoch=50)
metric = dc.metrics.Metric(dc.metrics.pearson_r2_score)
print('training set score:', model.evaluate(train_dataset, [metric]))
print('test set score:', model.evaluate(test_dataset, [metric]))
```

%% Output

    training set score: {'pearson_r2_score': 0.9794976301693646}
    test set score: {'pearson_r2_score': 0.7259302601080715}
    training set score: {'pearson_r2_score': 0.9787445597470444}
    test set score: {'pearson_r2_score': 0.736905850092889}

%% Cell type:markdown id: tags:

## TorchModel

`TorchModel` works just like `KerasModel`, except it wraps a `torch.nn.Module`.  Let's use PyTorch to create another model just like the previous one and train it on the same data.

%% Cell type:code id: tags:

``` python
import torch

pytorch_model = torch.nn.Sequential(
    torch.nn.Linear(1024, 1000),
    torch.nn.ReLU(),
    torch.nn.Dropout(0.5),
    torch.nn.Linear(1000, 1)
)
model = dc.models.TorchModel(pytorch_model, dc.models.losses.L2Loss())

model.fit(train_dataset, nb_epoch=50)
print('training set score:', model.evaluate(train_dataset, [metric]))
print('test set score:', model.evaluate(test_dataset, [metric]))
```

%% Output

    training set score: {'pearson_r2_score': 0.9799654867822989}
    test set score: {'pearson_r2_score': 0.7199433832205063}
    training set score: {'pearson_r2_score': 0.9798256761766225}
    test set score: {'pearson_r2_score': 0.7256745385608444}

%% Cell type:markdown id: tags:

## Computing Losses

Now let's see a more advanced example.  In the above models, the loss was computed directly from the model's output.  Often that is fine, but not always.  Consider a classification model that outputs a probability distribution.  While it is possible to compute the loss from the probabilities, it is more numerically stable to compute it from the logits.

To do this, we create a model that returns multiple outputs, both probabilities and logits.  `KerasModel` and `TorchModel` let you specify a list of "output types".  If a particular output has type `'prediction'`, that means it is a normal output that should be returned when you call `predict()`.  If it has type `'loss'`, that means it should be passed to the loss function in place of the normal outputs.

Sequential models do not allow multiple outputs, so instead we use a subclassing style model.

%% Cell type:code id: tags:

``` python
class ClassificationModel(tf.keras.Model):

    def __init__(self, n_classes):
    def __init__(self):
        super(ClassificationModel, self).__init__()
        self.dense1 = tf.keras.layers.Dense(1000, activation='relu')
        self.dense2 = tf.keras.layers.Dense(n_classes)
        self.dense2 = tf.keras.layers.Dense(1)

    def call(self, inputs, training=False):
        y = self.dense1(inputs)
        if training:
            y = tf.nn.dropout(y, 0.5)
        logits = self.dense2(y)
        output = tf.nn.softmax(logits)
        output = tf.nn.sigmoid(logits)
        return output, logits

keras_model = ClassificationModel(2)
keras_model = ClassificationModel()
output_types = ['prediction', 'loss']
model = dc.models.KerasModel(keras_model, dc.models.losses.SoftmaxCrossEntropy(), output_types=output_types)
model = dc.models.KerasModel(keras_model, dc.models.losses.SigmoidCrossEntropy(), output_types=output_types)
```

%% Cell type:markdown id: tags:

We can train our model on the BACE dataset.  This is a binary classification task that tries to predict whether a molecule will inhibit the enzyme BACE-1.

%% Cell type:code id: tags:

``` python
tasks, datasets, transformers = dc.molnet.load_bace_classification(feturizer='ECFP', split='scaffold')
train_dataset, valid_dataset, test_dataset = datasets
model.fit(train_dataset, nb_epoch=100)
metric = dc.metrics.Metric(dc.metrics.roc_auc_score)
print('training set score:', model.evaluate(train_dataset, [metric]))
print('test set score:', model.evaluate(test_dataset, [metric]))
```

%% Output

    training set score: {'roc_auc_score': 0.4268401201369002}
    test set score: {'roc_auc_score': 0.22269021739130435}
    training set score: {'roc_auc_score': 0.9996116504854369}
    test set score: {'roc_auc_score': 0.7701992753623188}

%% Cell type:markdown id: tags:

## Other Features

`KerasModel` and `TorchModel` have lots of other features.  Here are some of the more important ones.

- Automatically saving checkpoints during training.
- Logging progress to the console, to [TensorBoard](https://www.tensorflow.org/tensorboard), or to [Weights & Biases](https://docs.wandb.com/).
- Custom loss functions that you define with a function of the form `f(outputs, labels, weights)`.
- Early stopping using the `ValidationCallback` class.
- Loading parameters from pre-trained models.
- Estimating uncertainty in model outputs.
- Identifying important features through saliency mapping.

By wrapping your own models in a `KerasModel` or `TorchModel`, you get immediate access to all these features.  See the API documentation for full details on them.