protac_degradation_predictor package
Subpackages
Submodules
protac_degradation_predictor.config module
- class protac_degradation_predictor.config.Config(morgan_radius: int = 10, fingerprint_size: int = 256, protein_embedding_size: int = 1024, cell_embedding_size: int = 768, dmax_threshold: float = 0.6, pdc50_threshold: float = 6.0, active_label: str = 'Active (Dmax 0.6, pDC50 6.0)', e3_ligase2uniprot: dict = <factory>)
Bases:
object
- Parameters:
morgan_radius (int)
fingerprint_size (int)
protein_embedding_size (int)
cell_embedding_size (int)
dmax_threshold (float)
pdc50_threshold (float)
active_label (str)
e3_ligase2uniprot (dict)
- morgan_radius: int = 10
- fingerprint_size: int = 256
- protein_embedding_size: int = 1024
- cell_embedding_size: int = 768
- dmax_threshold: float = 0.6
- pdc50_threshold: float = 6.0
- active_label: str = 'Active (Dmax 0.6, pDC50 6.0)'
- e3_ligase2uniprot: dict
protac_degradation_predictor.data_utils module
- protac_degradation_predictor.data_utils.avail_e3_ligases()
Get the available E3 ligases.
- Returns:
The available E3 ligases.
- Return type:
List[str]
- protac_degradation_predictor.data_utils.avail_cell_lines()
Get the available cell lines.
- Returns:
The available cell lines.
- Return type:
List[str]
- protac_degradation_predictor.data_utils.avail_uniprots()
Get the available Uniprot IDs.
- Returns:
The available Uniprot IDs.
- Return type:
List[str]
- protac_degradation_predictor.data_utils.get_fingerprint(smiles, morgan_fpgen=None)
Get the Morgan fingerprint of a molecule.
- Parameters:
smiles (str) – The SMILES string of the molecule.
morgan_fpgen – The Morgan fingerprint generator.
- Returns:
The Morgan fingerprint.
- Return type:
np.ndarray
- protac_degradation_predictor.data_utils.is_active(DC50, Dmax, pDC50_threshold=7.0, Dmax_threshold=0.8, oring=False)
Check if a PROTAC is active based on DC50 and Dmax. :param DC50: DC50 in nM :type DC50: float :param Dmax: Dmax in % :type Dmax: float
- Returns:
True if active, False if inactive, np.nan if either DC50 or Dmax is NaN
- Return type:
bool
- Parameters:
DC50 (float)
Dmax (float)
pDC50_threshold (float)
Dmax_threshold (float)
oring (bool)
- protac_degradation_predictor.data_utils.load_curated_dataset()
Load the curated PROTAC dataset as described in the paper: https://arxiv.org/abs/2406.02637
- Returns:
The curated PROTAC dataset.
- Return type:
pd.DataFrame
protac_degradation_predictor.optuna_utils module
- protac_degradation_predictor.optuna_utils.get_dataframe_stats(train_df=None, val_df=None, test_df=None, active_label='Active')
Get some statistics from the dataframes.
- Parameters:
train_df (pd.DataFrame) – The training set.
val_df (pd.DataFrame) – The validation set.
test_df (pd.DataFrame) – The test set.
- Return type:
Dict
- protac_degradation_predictor.optuna_utils.get_majority_vote_metrics(test_preds, test_df, active_label='Active')
Get the majority vote metrics.
- Parameters:
test_preds (List)
test_df (DataFrame)
active_label (str)
- Return type:
Dict
- protac_degradation_predictor.optuna_utils.get_suggestion(trial, dtype, hparams_range)
- protac_degradation_predictor.optuna_utils.pytorch_model_objective(trial, protein2embedding, cell2embedding, smiles2fp, train_val_df, kf, groups=None, test_df=None, hparams_ranges=None, fast_dev_run=False, active_label='Active', disabled_embeddings=[], max_epochs=100, use_logger=False, logger_save_dir='logs', logger_name='cv_model', enable_checkpointing=False)
Objective function for hyperparameter optimization.
- Parameters:
trial (optuna.Trial) – The Optuna trial object.
train_df (pd.DataFrame) – The training set.
val_df (pd.DataFrame) – The validation set.
hparams_ranges (List[Dict[str, Any]]) – NOT IMPLEMENTED YET. Hyperparameters ranges. The list must be of a tuple of the type of hparam to suggest (‘int’, ‘float’, or ‘categorical’), and the dictionary must contain the arguments of the corresponding trial.suggest method.
fast_dev_run (bool) – Whether to run a fast development run.
active_label (str) – The active label column.
disabled_embeddings (List[str]) – The list of disabled embeddings.
protein2embedding (Dict)
cell2embedding (Dict)
smiles2fp (Dict)
train_val_df (DataFrame)
kf (StratifiedKFold | StratifiedGroupKFold)
groups (array | None)
test_df (DataFrame | None)
max_epochs (int)
use_logger (bool)
logger_save_dir (str)
logger_name (str)
enable_checkpointing (bool)
- Return type:
float
- protac_degradation_predictor.optuna_utils.hyperparameter_tuning_and_training(protein2embedding, cell2embedding, smiles2fp, train_val_df, test_df, kf, groups=None, split_type='standard', n_models_for_test=3, fast_dev_run=False, n_trials=50, logger_save_dir='logs', logger_name='protac_hparam_search', active_label='Active', max_epochs=100, study_filename=None, force_study=False)
Hyperparameter tuning and training of a PROTAC model.
- Parameters:
protein2embedding (Dict) – The protein to embedding dictionary.
cell2embedding (Dict) – The cell to embedding dictionary.
smiles2fp (Dict) – The SMILES to fingerprint dictionary.
train_val_df (pd.DataFrame) – The training and validation set.
test_df (pd.DataFrame) – The test set.
kf (StratifiedKFold | StratifiedGroupKFold) – The KFold object.
groups (np.array) – The groups for the StratifiedGroupKFold.
split_type (str) – The split type of the current study. Used for reporting.
n_models_for_test (int) – The number of models to train for the test set.
fast_dev_run (bool) – Whether to run a fast development run.
n_trials (int) – The number of trials for the hyperparameter search.
logger_save_dir (str) – The logger save directory.
logger_name (str) – The logger name.
active_label (str) – The active label column.
max_epochs (int) – The maximum number of epochs.
study_filename (str) – The study filename.
force_study (bool) – Whether to force the study.
- Returns:
The trained model, the trainer, and the best metrics.
- Return type:
tuple
protac_degradation_predictor.optuna_utils_xgboost module
- protac_degradation_predictor.optuna_utils_xgboost.get_confidence_scores(y, y_pred, threshold=0.5)
- protac_degradation_predictor.optuna_utils_xgboost.train_and_evaluate_xgboost(protein2embedding, cell2embedding, smiles2fp, train_df, val_df, params, test_df=None, active_label='Active', num_boost_round=100, shuffle_train_data=False)
Train and evaluate an XGBoost model with the given parameters.
- Parameters:
train_df (pd.DataFrame) – The training and validation data.
test_df (pd.DataFrame) – The test data.
params (dict) – Hyperparameters for the XGBoost model.
active_label (str) – The active label column.
num_boost_round (int) – Maximum number of epochs.
protein2embedding (Dict)
cell2embedding (Dict)
smiles2fp (Dict)
val_df (DataFrame)
shuffle_train_data (bool)
- Returns:
The trained model, test predictions, and metrics.
- Return type:
tuple
- protac_degradation_predictor.optuna_utils_xgboost.xgboost_model_objective(trial, protein2embedding, cell2embedding, smiles2fp, train_val_df, kf, groups=None, active_label='Active', num_boost_round=100, model_name=None)
Objective function for hyperparameter optimization with XGBoost.
- Parameters:
trial (optuna.Trial) – The Optuna trial object.
train_val_df (pd.DataFrame) – The training and validation data.
kf (StratifiedKFold) – Stratified K-Folds cross-validator.
test_df (Optional[pd.DataFrame]) – The test data.
active_label (str) – The active label column.
num_boost_round (int) – Maximum number of epochs.
model_name (Optional[str]) – The prefix name of the CV models to save, if supplied. Used as: f”{model_name}_fold_{k}.json”
protein2embedding (Dict)
cell2embedding (Dict)
smiles2fp (Dict)
groups (array | None)
- Return type:
float
- protac_degradation_predictor.optuna_utils_xgboost.xgboost_hyperparameter_tuning_and_training(protein2embedding, cell2embedding, smiles2fp, train_val_df, test_df, kf, groups=None, split_type='random', n_models_for_test=3, n_trials=50, active_label='Active', num_boost_round=100, study_filename=None, force_study=False, model_name=None)
Hyperparameter tuning and training of an XGBoost model.
- Parameters:
train_val_df (pd.DataFrame) – The training and validation data.
test_df (pd.DataFrame) – The test data.
kf (StratifiedKFold) – Stratified K-Folds cross-validator.
groups (Optional[np.array]) – Group labels for the samples used while splitting the dataset into train/test set.
split_type (str) – Type of the data split. Used for reporting information.
n_models_for_test (int) – Number of models to train for testing.
fast_dev_run (bool) – Whether to run a fast development run.
n_trials (int) – Number of trials for hyperparameter optimization.
logger_save_dir (str) – Directory to save logs.
logger_name (str) – Name of the logger.
active_label (str) – The active label column.
num_boost_round (int) – Maximum number of epochs.
study_filename (Optional[str]) – File name to save/load the Optuna study.
force_study (bool) – Whether to force the study optimization even if the study file exists.
protein2embedding (Dict)
cell2embedding (Dict)
smiles2fp (Dict)
model_name (str | None)
- Returns:
A dictionary containing reports from the CV and test.
- Return type:
dict
protac_degradation_predictor.protac_dataset module
- class protac_degradation_predictor.protac_dataset.PROTAC_Dataset(protac_df, protein2embedding, cell2embedding, smiles2fp, use_smote=False, oversampler=None, active_label='Active', disabled_embeddings=[], scaler=None, use_single_scaler=None, shuffle_embedding_prob=0.0)
Bases:
Dataset
- Parameters:
protac_df (DataFrame)
protein2embedding (Dict[str, ndarray])
cell2embedding (Dict[str, ndarray])
smiles2fp (Dict[str, ndarray])
use_smote (bool)
oversampler (SMOTE | ADASYN | None)
active_label (str)
disabled_embeddings (List[Literal['smiles', 'poi', 'e3', 'cell']])
scaler (StandardScaler | Dict[str, StandardScaler] | None)
use_single_scaler (bool | None)
shuffle_embedding_prob (float)
- get_smiles_emb_dim()
- get_protein_emb_dim()
- get_cell_emb_dim()
- apply_smote()
- fit_scaling(use_single_scaler=False, **scaler_kwargs)
Fit the scalers for the data and save them in the dataset class.
- Parameters:
use_single_scaler (bool) – Whether to use a single scaler for all features.
scaler_kwargs – Keyword arguments for the StandardScaler.
- Returns:
The fitted scalers.
- Return type:
dict
- apply_scaling(scalers, use_single_scaler=False)
Apply scaling to the data.
- Parameters:
scalers (dict) – The scalers for each feature.
use_single_scaler (bool) – Whether to use a single scaler for all features.
- get_numpy_arrays(component=None)
Get the numpy arrays for the dataset.
- Parameters:
component (str) – The component to get the numpy arrays for. Defaults to None, i.e., get a single stacked array.
- Returns:
The numpy arrays for the dataset. The first element is the input array, and the second element is the output array.
- Return type:
tuple
- protac_degradation_predictor.protac_dataset.get_datasets(train_df, val_df, test_df=None, protein2embedding=None, cell2embedding=None, smiles2fp=None, smote_k_neighbors=5, active_label='Active', disabled_embeddings=[], scaler=None, use_single_scaler=None, apply_scaling=False, shuffle_embedding_prob=0.0)
Get the datasets for training the PROTAC model.
- Parameters:
train_df (pd.DataFrame) – The training data.
val_df (pd.DataFrame) – The validation data.
test_df (pd.DataFrame) – The test data.
protein2embedding (dict) – Dictionary of protein embeddings.
cell2embedding (dict) – Dictionary of cell line embeddings.
smiles2fp (dict) – Dictionary of SMILES to fingerprint.
use_smote (bool) – Whether to use SMOTE for oversampling.
smote_k_neighbors (int) – The number of neighbors to use for SMOTE.
active_label (str) – The active label column.
disabled_embeddings (list) – The list of embeddings to disable.
scaler (StandardScaler | dict) – The scaler to use for the embeddings.
use_single_scaler (bool) – Whether to use a single scaler for all features.
apply_scaling (bool) – Whether to apply scaling to the data now. Defaults to False (the Pytorch Lightning model does that).
shuffle_embedding_prob (float)
- Return type:
Tuple[PROTAC_Dataset, PROTAC_Dataset, PROTAC_Dataset | None]
- class protac_degradation_predictor.protac_dataset.PROTAC_DataModule(*args, **kwargs)
Bases:
LightningDataModule
PyTorch Lightning DataModule for the PROTAC dataset.
TODO: Work in progress. It would be nice to wrap all information into a single class, but it is not clear how to do it yet due to cross-validation and the need to split the data into training, validation, and test sets accordingly.
- Parameters:
protac_csv_filepath (str) – The path to the PROTAC CSV file.
protein2embedding_filepath (str) – The path to the protein to embedding dictionary.
cell2embedding_filepath (str) – The path to the cell line to embedding dictionary.
pDC50_threshold (float) – The threshold for the pDC50 value to consider a PROTAC active.
Dmax_threshold (float) – The threshold for the Dmax value to consider a PROTAC active.
use_smote (bool) – Whether to use SMOTE for oversampling.
smote_k_neighbors (int) – The number of neighbors to use for SMOTE.
active_label (str) – The column containing the active/inactive information.
disabled_embeddings (list) – The list of embeddings to disable.
scaler (StandardScaler | dict) – The scaler to use for the embeddings.
use_single_scaler (bool) – Whether to use a single scaler for all features.
- setup(stage)
- Parameters:
stage (str)
- train_dataloader()
- val_dataloader()
- test_dataloader()
- static get_random_split_indices(active_df, test_split)
Get the indices of the test set using a random split.
- Parameters:
active_df (pd.DataFrame) – The DataFrame containing the active PROTACs.
test_split (float) – The percentage of the active PROTACs to use as the test set.
- Returns:
The indices of the test set.
- Return type:
pd.Index
- static get_e3_ligase_split_indices(active_df)
Get the indices of the test set using the E3 ligase split.
- Parameters:
active_df (pd.DataFrame) – The DataFrame containing the active PROTACs.
- Returns:
The indices of the test set.
- Return type:
pd.Index
- static get_smiles2fp_and_avg_tanimoto(protac_df)
Get the SMILES to fingerprint dictionary and the average Tanimoto similarity.
- Parameters:
protac_df (pd.DataFrame) – The DataFrame containing the PROTACs.
- Returns:
The SMILES to fingerprint dictionary and the average Tanimoto similarity.
- Return type:
tuple
- static get_tanimoto_split_indices(active_df, active_label, test_split, n_bins_tanimoto=200)
Get the indices of the test set using the Tanimoto-based split.
- Parameters:
active_df (pd.DataFrame) – The DataFrame containing the active PROTACs.
n_bins_tanimoto (int) – The number of bins to use for the Tanimoto similarity.
active_label (str)
test_split (float)
- Returns:
The indices of the test set.
- Return type:
pd.Index
- static get_target_split_indices(active_df, active_label, test_split)
Get the indices of the test set using the target-based split.
- Parameters:
active_df (pd.DataFrame) – The DataFrame containing the active PROTACs.
active_label (str) – The column containing the active/inactive information.
test_split (float) – The percentage of the active PROTACs to use as the test set.
- Returns:
The indices of the test set.
- Return type:
pd.Index
protac_degradation_predictor.protac_degradation_predictor module
- protac_degradation_predictor.protac_degradation_predictor.get_protac_active_proba(protac_smiles, e3_ligase, target_uniprot, cell_line, device='cpu', use_models_from_cv=False, use_xgboost_models=False, study_type='standard')
Predict the probability of a PROTAC being active.
- Parameters:
protac_smiles (str | List[str]) – The SMILES of the PROTAC.
e3_ligase (str | List[str]) – The Uniprot ID of the E3 ligase.
target_uniprot (str | List[str]) – The Uniprot ID of the target protein.
cell_line (str | List[str]) – The cell line identifier.
device (str) – The device to run the model on.
use_models_from_cv (bool) – Whether to use the models from cross-validation.
use_xgb_models (bool) – Whether to use the XGBoost models.
study_type (str) – Use models trained on the specified study. Options are ‘standard’, ‘similarity’, ‘target’.
use_xgboost_models (bool)
- Returns:
The predictions of the model. The dictionary contains the following: ‘preds’, ‘mean’, ‘majority_vote’. The ‘preds’ key contains the predictions of all models with shape: (n_models, batch_size), ‘mean’ contains the mean prediction, and ‘majority_vote’ contains the majority vote.
- Return type:
Dict[str, np.ndarray]
- protac_degradation_predictor.protac_degradation_predictor.is_protac_active(protac_smiles, e3_ligase, target_uniprot, cell_line, device='cpu', proba_threshold=0.5, use_majority_vote=False, use_models_from_cv=False, use_xgboost_models=False, study_type='standard')
Predict whether a PROTAC is active or not.
- Parameters:
protac_smiles (str) – The SMILES of the PROTAC.
e3_ligase (str) – The Uniprot ID of the E3 ligase.
target_uniprot (str) – The Uniprot ID of the target protein.
cell_line (str) – The cell line identifier.
device (str) – The device to run the model on.
proba_threshold (float) – The probability threshold.
use_majority_vote (bool) – Whether to use the majority vote.
use_models_from_cv (bool) – Whether to use the models from cross-validation.
use_xgboost_models (bool) – Whether to use the XGBoost models.
study_type (str) – Use models trained on the specified study. Options are ‘standard’, ‘similarity’, ‘target’.
- Returns:
Whether the PROTAC is active or not.
- Return type:
bool
- protac_degradation_predictor.protac_degradation_predictor.get_protac_embedding(protac_smiles, e3_ligase, target_uniprot, cell_line, device='cpu', use_models_from_cv=False, study_type='standard')
Get the embeddings of a PROTAC or a list of PROTACs.
- Parameters:
protac_smiles (str | List[str]) – The SMILES of the PROTAC.
e3_ligase (str | List[str]) – The Uniprot ID of the E3 ligase.
target_uniprot (str | List[str]) – The Uniprot ID of the target protein.
cell_line (str | List[str]) – The cell line identifier.
device (str) – The device to run the model on.
use_models_from_cv (bool) – Whether to use the models from cross-validation.
study_type (str) – Use models trained on the specified study. Options are ‘standard’, ‘similarity’, ‘target’.
- Returns:
The embeddings of the given PROTAC. Each key is the name of the model and the value is the embedding, of shape: (batch_size, model_hidden_size). NOTE: Each model has its own hidden size, so the embeddings might have different dimensions.
- Return type:
Dict[str, np.ndarray]
protac_degradation_predictor.pytorch_models module
- class protac_degradation_predictor.pytorch_models.PROTAC_Predictor(hidden_dim, smiles_emb_dim=256, poi_emb_dim=1024, e3_emb_dim=1024, cell_emb_dim=768, dropout=0.2, join_embeddings='sum', use_batch_norm=False, disabled_embeddings=[])
Bases:
Module
- Parameters:
hidden_dim (int)
smiles_emb_dim (int)
poi_emb_dim (int)
e3_emb_dim (int)
cell_emb_dim (int)
dropout (float)
join_embeddings (Literal['beginning', 'concat', 'sum'])
use_batch_norm (bool)
disabled_embeddings (List[Literal['smiles', 'poi', 'e3', 'cell']])
- forward(poi_emb, e3_emb, cell_emb, smiles_emb, return_embeddings=False)
Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- T_destination = ~T_destination
- add_module(name, module)
Adds a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- Return type:
None
- apply(fn)
Applies
fn
recursively to every submodule (as returned by.children()
) as well as self. Typical use includes initializing the parameters of a model (see also nn-init-doc).- Parameters:
fn (
Module
-> None) – function to be applied to each submoduleself (T)
- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16()
Casts all floating point parameters and buffers to
bfloat16
datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- Parameters:
self (T)
- buffers(recurse=True)
Returns an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
- Return type:
Iterator[Tensor]
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children()
Returns an iterator over immediate children modules.
- Yields:
Module – a child module
- Return type:
Iterator[Module]
- cpu()
Moves all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- Parameters:
self (T)
- cuda(device=None)
Moves all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
self (T)
- Returns:
self
- Return type:
Module
- double()
Casts all floating point parameters and buffers to
double
datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- Parameters:
self (T)
- dump_patches: bool = False
- eval()
Sets the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.This is equivalent with
self.train(False)
.See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- Parameters:
self (T)
- extra_repr()
Set the extra representation of the module
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
str
- float()
Casts all floating point parameters and buffers to
float
datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- Parameters:
self (T)
- get_buffer(target)
Returns the buffer given by
target
if it exists, otherwise throws an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters:
target (str) – The fully-qualified string name of the buffer to look for. (See
get_submodule
for how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target
- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state()
Returns any extra state to include in the module’s state_dict. Implement this and a corresponding
set_extra_state()
for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target)
Returns the parameter given by
target
if it exists, otherwise throws an error.See the docstring for
get_submodule
for a more detailed explanation of this method’s functionality as well as how to correctly specifytarget
.- Parameters:
target (str) – The fully-qualified string name of the Parameter to look for. (See
get_submodule
for how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target
- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target)
Returns the submodule given by
target
if it exists, otherwise throws an error.For example, let’s say you have an
nn.Module
A
that looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )
(The diagram shows an
nn.Module
A
.A
has a nested submodulenet_b
, which itself has two submodulesnet_c
andlinear
.net_c
then has a submoduleconv
.)To check whether or not we have the
linear
submodule, we would callget_submodule("net_b.linear")
. To check whether we have theconv
submodule, we would callget_submodule("net_b.net_c.conv")
.The runtime of
get_submodule
is bounded by the degree of module nesting intarget
. A query againstnamed_modules
achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submodule
should always be used.- Parameters:
target (str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target
- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half()
Casts all floating point parameters and buffers to
half
datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- Parameters:
self (T)
- ipu(device=None)
Moves all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
self (T)
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict, strict=True)
Copies parameters and buffers from
state_dict
into this module and its descendants. Ifstrict
isTrue
, then the keys ofstate_dict
must exactly match the keys returned by this module’sstate_dict()
function.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dict
match the keys returned by this module’sstate_dict()
function. Default:True
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuple
withmissing_keys
andunexpected_keys
fields
Note
If a parameter or buffer is registered as
None
and its corresponding key exists instate_dict
,load_state_dict()
will raise aRuntimeError
.
- modules()
Returns an iterator over all modules in the network.
- Yields:
Module – a module in the network
- Return type:
Iterator[Module]
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix='', recurse=True, remove_duplicate=True)
Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
- Return type:
Iterator[Tuple[str, Tensor]]
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children()
Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
- Return type:
Iterator[Tuple[str, Module]]
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo=None, prefix='', remove_duplicate=True)
Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo (Set[Module] | None) – a memo to store the set of modules already added to the result
prefix (str) – a prefix that will be added to the name of the module
remove_duplicate (bool) – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
l
will be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix='', recurse=True, remove_duplicate=True)
Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
- Return type:
Iterator[Tuple[str, Parameter]]
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse=True)
Returns an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
- Return type:
Iterator[Parameter]
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook)
Registers a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()
and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type:
torch.utils.hooks.RemovableHandle
- Parameters:
hook (Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor])
- register_buffer(name, tensor, persistent=True)
Adds a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_mean
is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistent
toFalse
. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict
.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None
, then operations that run on buffers, such ascuda
, are ignored. IfNone
, the buffer is not included in the module’sstate_dict
.persistent (bool) – whether the buffer is part of this module’s
state_dict
.
- Return type:
None
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook, *, prepend=False, with_kwargs=False)
Registers a forward hook on the module.
The hook will be called every time after
forward()
has computed an output.If
with_kwargs
isFalse
or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()
is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargs
isTrue
, the forward hook will be passed thekwargs
given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True
, the providedhook
will be fired before all existingforward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward
hooks on thistorch.nn.modules.Module
. Note that globalforward
hooks registered withregister_module_forward_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If
True
, thehook
will be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)
Registers a forward pre-hook on the module.
The hook will be called every time before
forward()
is invoked.If
with_kwargs
is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward
. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargs
is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingforward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingforward_pre
hooks on thistorch.nn.modules.Module
. Note that globalforward_pre
hooks registered withregister_module_forward_pre_hook()
will fire before all hooks registered by this method. Default:False
with_kwargs (bool) – If true, the
hook
will be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook, prepend=False)
Registers a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_input
andgrad_output
are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_input
in subsequent computations.grad_input
will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_input
andgrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward
hooks on thistorch.nn.modules.Module
. Note that globalbackward
hooks registered withregister_module_full_backward_hook()
will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook, prepend=False)
Registers a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> Tensor or None
The
grad_output
is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_output
in subsequent computations. Entries ingrad_output
will beNone
for all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hook
will be fired before all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Otherwise, the providedhook
will be fired after all existingbackward_pre
hooks on thistorch.nn.modules.Module
. Note that globalbackward_pre
hooks registered withregister_module_full_backward_pre_hook()
will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Registers a post hook to be run after module’s
load_state_dict
is called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
module
argument is the current module that this hook is registered on, and theincompatible_keys
argument is aNamedTuple
consisting of attributesmissing_keys
andunexpected_keys
.missing_keys
is alist
ofstr
containing the missing keys andunexpected_keys
is alist
ofstr
containing the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()
withstrict=True
are affected by modifications the hook makes tomissing_keys
orunexpected_keys
, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True
, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()
- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name, module)
Alias for
add_module()
.- Parameters:
name (str)
module (Module | None)
- Return type:
None
- register_parameter(name, param)
Adds a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None
, then operations that run on parameters, such ascuda
, are ignored. IfNone
, the parameter is not included in the module’sstate_dict
.
- Return type:
None
- register_state_dict_pre_hook(hook)
These hooks will be called with arguments:
self
,prefix
, andkeep_vars
before callingstate_dict
onself
. The registered hooks can be used to perform pre-processing before thestate_dict
call is made.
- requires_grad_(requires_grad=True)
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_grad
attributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True
.self (T)
- Returns:
self
- Return type:
Module
- set_extra_state(state)
This function is called from
load_state_dict()
to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()
for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_()
- Parameters:
self (T)
- Return type:
T
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Returns a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
None
are not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()
also accepts positional arguments fordestination
,prefix
andkeep_vars
in order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destination
as it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDict
will be created and returned. Default:None
.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''
.keep_vars (bool, optional) – by default the
Tensor
s returned in the state dict are detached from autograd. If it’s set toTrue
, detaching will not be performed. Default:False
.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Moves and/or casts the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to()
, but only accepts floating point or complexdtype
s. In addition, this method will only cast the floating point or complex parameters and buffers todtype
(if given). The integral parameters and buffers will be moveddevice
, if that is given, but with dtypes unchanged. Whennon_blocking
is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device
) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype
) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format
) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device)
Moves the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device
) – The desired device of the parameters and buffers in this module.self (T)
- Returns:
self
- Return type:
Module
- train(mode=True)
Sets the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout
,BatchNorm
, etc.- Parameters:
mode (bool) – whether to set training mode (
True
) or evaluation mode (False
). Default:True
.self (T)
- Returns:
self
- Return type:
Module
- type(dst_type)
Casts all parameters and buffers to
dst_type
.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
self (T)
- Returns:
self
- Return type:
Module
- xpu(device=None)
Moves all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
self (T)
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none=True)
Sets gradients of all model parameters to zero. See similar function under
torch.optim.Optimizer
for more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()
for details.- Return type:
None
- training: bool
- class protac_degradation_predictor.pytorch_models.PROTAC_Model(*args, **kwargs)
Bases:
LightningModule
- Parameters:
hidden_dim (int)
smiles_emb_dim (int)
poi_emb_dim (int)
e3_emb_dim (int)
cell_emb_dim (int)
batch_size (int)
learning_rate (float)
dropout (float)
use_batch_norm (bool)
join_embeddings (Literal['beginning', 'concat', 'sum'])
train_dataset (PROTAC_Dataset)
val_dataset (PROTAC_Dataset)
test_dataset (PROTAC_Dataset)
disabled_embeddings (List[Literal['smiles', 'poi', 'e3', 'cell']])
apply_scaling (bool)
extra_optim_params (dict | None)
- initialize_scalers()
Initialize or reinitialize scalers based on dataset properties.
- apply_scalers()
Apply scalers to all datasets.
- scale_tensor(tensor, scaler, alpha=1e-10)
Scale a tensor using a scaler. This is done to avoid using numpy arrays (and stay on the same device).
- Parameters:
tensor (torch.Tensor) – The tensor to scale.
scaler (StandardScaler) – The scaler to use.
alpha (float)
- Returns:
The scaled tensor.
- Return type:
torch.Tensor
- forward(poi_emb, e3_emb, cell_emb, smiles_emb, prescaled_embeddings=True, return_embeddings=False)
- step(batch, batch_idx, stage)
- training_step(batch, batch_idx)
- validation_step(batch, batch_idx)
- test_step(batch, batch_idx)
- configure_optimizers()
- predict_step(batch, batch_idx)
- train_dataloader()
- val_dataloader()
- test_dataloader()
- on_save_checkpoint(checkpoint)
Serialize the scalers to the checkpoint.
- on_load_checkpoint(checkpoint)
Deserialize the scalers from the checkpoint.
- protac_degradation_predictor.pytorch_models.get_confidence_scores(true_ds, y_preds, threshold=0.5)
Get the mean value of the predictions for the false positives and false negatives.
- Parameters:
true_ds (PROTAC_Dataset | torch.Tensor | np.ndarray) – The true labels
y_preds (torch.Tensor | np.ndarray) – The predictions
threshold (float) – The threshold to use for the predictions
- Returns:
The mean value of the predictions for the false positives and false negatives.
- Return type:
Tuple[float, float]
- protac_degradation_predictor.pytorch_models.train_model(protein2embedding, cell2embedding, smiles2fp, train_df, val_df, test_df=None, hidden_dim=768, batch_size=128, learning_rate=2e-05, beta1=0.9, beta2=0.999, eps=1e-08, dropout=0.2, max_epochs=50, use_batch_norm=False, join_embeddings='sum', smote_k_neighbors=5, apply_scaling=True, active_label='Active', fast_dev_run=False, use_logger=True, logger_save_dir='../logs', logger_name='protac', enable_checkpointing=False, checkpoint_model_name='protac', disabled_embeddings=[], return_predictions=False, shuffle_embedding_prob=0.0, use_smote=False)
Train a PROTAC model using the given datasets and hyperparameters.
- Parameters:
protein2embedding (dict) – A dictionary mapping protein identifiers to embeddings.
cell2embedding (dict) – A dictionary mapping cell line identifiers to embeddings.
smiles2fp (dict) – A dictionary mapping SMILES strings to fingerprints.
train_df (pd.DataFrame) – The training dataframe.
val_df (pd.DataFrame) – The validation dataframe.
test_df (Optional[pd.DataFrame]) – The test dataframe.
hidden_dim (int) – The hidden dimension of the model
batch_size (int) – The batch size
learning_rate (float) – The learning rate
dropout (float) – The dropout rate
max_epochs (int) – The maximum number of epochs
use_batch_norm (bool) – Whether to use batch normalization
join_embeddings (Literal['beginning', 'concat', 'sum']) – How to join the embeddings
smote_k_neighbors (int) – The number of neighbors to use in SMOTE
use_smote (bool) – Whether to use SMOTE
apply_scaling (bool) – Whether to apply scaling to the embeddings
active_label (str) – The name of the active label. Default: ‘Active’
fast_dev_run (bool) – Whether to run a fast development run (see PyTorch Lightning documentation)
use_logger (bool) – Whether to use a logger
logger_save_dir (str) – The directory to save the logs
logger_name (str) – The name of the logger
enable_checkpointing (bool) – Whether to enable checkpointing
checkpoint_model_name (str) – The name of the model for checkpointing
disabled_embeddings (list) – List of disabled embeddings. Can be ‘poi’, ‘e3’, ‘cell’, ‘smiles’
return_predictions (bool) – Whether to return predictions on the validation and test sets
beta1 (float)
beta2 (float)
eps (float)
shuffle_embedding_prob (float)
- Returns:
The trained model, the trainer, and the metrics over the validation and test sets.
- Return type:
tuple
- protac_degradation_predictor.pytorch_models.evaluate_model(model, trainer, val_ds, test_ds=None, batch_size=128)
Evaluate a PROTAC model using the given datasets.
- Parameters:
model (PROTAC_Model)
trainer (pytorch_lightning.Trainer)
val_ds (PROTAC_Dataset)
test_ds (PROTAC_Dataset | None)
batch_size (int)
- Return type:
tuple
- protac_degradation_predictor.pytorch_models.load_model(ckpt_path)
Load a PROTAC model from a checkpoint.
- Parameters:
ckpt_path (str) – The path to the checkpoint.
- Returns:
The loaded model.
- Return type:
protac_degradation_predictor.sklearn_models module
- protac_degradation_predictor.sklearn_models.train_sklearn_model(clf, protein2embedding, cell2embedding, smiles2fp, train_df, val_df, test_df=None, active_label='Active', use_single_scaler=True)
Train a classifier model on train and val sets and evaluate it on a test set.
- Parameters:
clf (ClassifierMixin) – The classifier model to train and evaluate.
train_df (pd.DataFrame) – The training set.
val_df (pd.DataFrame) – The validation set.
test_df (Optional[pd.DataFrame]) – The test set.
protein2embedding (Dict)
cell2embedding (Dict)
smiles2fp (Dict)
active_label (str)
use_single_scaler (bool)
- Returns:
The trained model and the metrics.
- Return type:
Tuple[ClassifierMixin, nn.ModuleDict]
- protac_degradation_predictor.sklearn_models.suggest_random_forest(trial)
Suggest hyperparameters for a Random Forest classifier.
- Parameters:
trial (optuna.Trial) – The Optuna trial object.
- Returns:
The Random Forest classifier with the suggested hyperparameters.
- Return type:
ClassifierMixin
- protac_degradation_predictor.sklearn_models.suggest_logistic_regression(trial)
Suggest hyperparameters for a Logistic Regression classifier.
- Parameters:
trial (optuna.Trial) – The Optuna trial object.
- Returns:
The Logistic Regression classifier with the suggested hyperparameters.
- Return type:
ClassifierMixin
- protac_degradation_predictor.sklearn_models.suggest_svc(trial)
Suggest hyperparameters for an SVC classifier.
- Parameters:
trial (optuna.Trial) – The Optuna trial object.
- Returns:
The SVC classifier with the suggested hyperparameters.
- Return type:
ClassifierMixin
- protac_degradation_predictor.sklearn_models.suggest_gradient_boosting(trial)
Suggest hyperparameters for a Gradient Boosting classifier.
- Parameters:
trial (optuna.Trial) – The Optuna trial object.
- Returns:
The Gradient Boosting classifier with the suggested hyperparameters.
- Return type:
ClassifierMixin