!pip install --pre deepchem

"""
Explanation: 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.
Colab
This tutorial and the rest in this sequence are designed to be done in Google colab. If you'd like to open this notebook in colab, you can use the following link.
End of explanation
"""


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())

"""
Explanation: There are actually two different approaches you can take to using TensorFlow or PyTorch models with DeepChem.  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.
End of explanation
"""


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]))

"""
Explanation: 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)?
End of explanation
"""


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]))

"""
Explanation: 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.
End of explanation
"""


class ClassificationModel(tf.keras.Model):
    
    def __init__(self):
        super(ClassificationModel, self).__init__()
        self.dense1 = tf.keras.layers.Dense(1000, activation='relu')
        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.sigmoid(logits)
        return output, logits

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

"""
Explanation: 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.
End of explanation
"""


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]))

"""
Explanation: 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.
End of explanation
"""


@manual{Intro1, 
 title={5}, 
 organization={DeepChem},
 author={Ramsundar, Bharath}, 
 howpublished = {\url{https://github.com/deepchem/deepchem/blob/master/examples/tutorials/Creating_Models_with_TensorFlow_and_PyTorch.ipynb}}, 
 year={2021}, 
} 

"""
Explanation: 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, or to Weights & Biases.
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.
Congratulations! Time to join the Community!
Congratulations on completing this tutorial notebook! If you enjoyed working through the tutorial, and want to continue working with DeepChem, we encourage you to finish the rest of the tutorials in this series. You can also help the DeepChem community in the following ways:
Star DeepChem on GitHub
This helps build awareness of the DeepChem project and the tools for open source drug discovery that we're trying to build.
Join the DeepChem Gitter
The DeepChem Gitter hosts a number of scientists, developers, and enthusiasts interested in deep learning for the life sciences. Join the conversation!
Citing This Tutorial
If you found this tutorial useful please consider citing it using the provided BibTeX.
End of explanation
"""


