liveBook · Manning

PyTorch

As explained in Build AI Drug Discovery Pipelines

PyTorch is an open-source machine-learning framework for building and training neural networks with tensor computation and automatic differentiation.

PyTorch is an open-source, Python-based deep learning framework for constructing, training, and evaluating neural networks. In drug discovery, it can support ligand-based virtual screening: predicting compound activity against a target so that promising candidates can be prioritized. section 8.1.2 section 8.3

PyTorch uses tensors, multidimensional arrays that hold model inputs, outputs, and parameters. A tensor has a shape, a data type, and a device such as a CPU or GPU. Tensor operations include reshaping, indexing, and matrix multiplication. section 8.1.2 section 8.3

>>> Two-dimensional tensor: tensor([[1, 2], [3, 4]])
print(f"Shape of tensor: {tensor_2d.shape}")
>>> Shape of tensor: torch.Size([2, 2])
print(f"Data type of tensor: {tensor_2d.dtype}")
>>> Data type of tensor: torch.int64
print(f"Device tensor is stored on: {tensor_2d.device}")
>>> Device tensor is stored on: cpu
 

Inspect a two-dimensional tensor’s shape, data type, and device before using it in a model. section 8.1.2

A practical molecular prediction workflow has four stages:

  • Split compound data into training, validation, and test sets. A scaffold split groups molecules by structural scaffold when separating training and test data. section 8.1.2
  • Convert molecular structures to numerical fingerprints and package them with activity values in a Dataset. DataLoader supplies batches to the model; the training loader shuffles its data. section 8.1.2
  • Place the neural network on an available device, choose a loss function and optimizer, and train while monitoring validation performance. A learning-rate scheduler can adjust the optimizer during training. section 8.1.2 section 8.3
  • Evaluate predictions on held-out test data and save the model parameters for later reuse. section 8.1.2
Listing 8.3 MoleculeDataset Data Loader
def smiles_to_fp(smiles, fp_size=2048):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return None
    mfpgen = rdFingerprintGenerator.GetMorganGenerator(
        radius=3, fpSize=fp_size
    )
    fp = mfpgen.GetFingerprint(mol)
    arr = np.zeros((fp_size,), dtype=np.int8)
    DataStructs.ConvertToNumpyArray(fp, arr)
    return arr
 
class MoleculeDataset(Dataset):
    def __init__(self, smiles, activities):
        self.smiles = smiles
        self.activities = activities
        self.fingerprints = [smiles_to_fp(s) for s in smiles]
        
    def __len__(self):
        return len(self.smiles)
    
    def __getitem__(self, idx):
        fp = torch.tensor(self.fingerprints[idx], dtype=torch.float32)
        activity = torch.tensor([self.activities[idx]], dtype=torch.float32)
        return fp, activity
 

See how SMILES molecular representations become fingerprints and float tensors paired with activity values. section 8.1.2

Kinase activity prediction

An EGFR compound dataset supplies molecular structures and activity values for a neural network. The workflow uses mean squared error loss and the Adam optimizer, then evaluates the trained model on a scaffold-split test set. Its reported test mean squared error is 0.9249 and mean absolute error is 0.7274; these figures describe this particular test set, not a guarantee for new compounds. section 8.1.2

criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
scheduler = ReduceLROnPlateau(
    optimizer, mode='min', factor=0.5, patience=5
)
 
train_model(
    model, train_loader, val_loader, criterion, optimizer,
    scheduler, device, num_epochs=50
)
 

Inspect the loss, optimizer, scheduler, and training call used in the kinase workflow. section 8.1.2

A compatible GPU can accelerate computation, but the demonstrated workflow also runs on a CPU. Check availability with torch.cuda.is_available() before choosing a device. section 8.1.2

How Build AI Drug Discovery Pipelines covers it

How deep it goes
Works through tensors and a molecular prediction workflow, then addresses neural-network mechanisms without attempting comprehensive PyTorch coverage.
Examples
Demonstrates tensor operations and an EGFR compound-activity model with test-set error metrics.
What you can do after
Apply it via PyTorch to prepare molecular data, train a neural network, evaluate predictions, and save model parameters.
How it connects
Connects tensors and neural networks with molecular fingerprints, scaffold splitting, optimization, and virtual screening.

Also explained in

Compare how 14 books explain PyTorch →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build AI Drug Discovery Pipelines. The section links point to the parts of the book it draws on.