### Install unimol_tools from Source Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/installation.md Steps to install unimol_tools by cloning the repository and running the setup script. ```python ## Dependencies installation pip install -r requirements.txt ## Clone repository git clone https://github.com/deepmodeling/unimol_tools.git cd unimol_tools ## Install python setup.py install ``` -------------------------------- ### Install unimol_tools from PyPI Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/installation.md Recommended installation method using pip. Install huggingface_hub for automatic model downloads. ```bash pip install unimol_tools ``` ```bash pip install huggingface_hub ``` -------------------------------- ### Install UniMol Tools from Source Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Installs the latest version of UniMol tools by cloning the repository and installing dependencies and the package itself. ```bash git clone https://github.com/deepmodeling/unimol_tools.git cd unimol_tools pip install -r requirements.txt python setup.py install ``` -------------------------------- ### Install UniMol Tools from PyPI Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Recommended installation for the stable version of UniMol tools. Ensure PyTorch is installed with CUDA support if applicable. ```bash pip install unimol_tools --upgrade ``` -------------------------------- ### Install huggingface_hub Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/weight.md Install the `huggingface_hub` library using pip. This is recommended for automatic downloading of Uni-Mol models. ```bash pip install huggingface_hub ``` -------------------------------- ### Multi-node Pretraining Setup Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Configure environment variables and torchrun arguments for multi-node distributed pretraining. Specify node count, GPUs per node, rank, master address, and port. ```bash export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 export HYDRA_FULL_ERROR=1 export OMP_NUM_THREADS=1 torchrun --nnodes=2 --nproc_per_node=8 --node_rank=0 \ --master_addr= --master_port= \ -m unimol_tools.cli.run_pretrain ... ``` -------------------------------- ### Set Master Address and Port for Multi-Node Training Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Configure `MASTER_ADDR` and `MASTER_PORT` environment variables for multi-node training. This example sets them to 'localhost' and '19198'. ```bash export MASTER_ADDR='localhost' export MASTER_PORT='19198' ``` -------------------------------- ### Run Pre-training with CSV Dataset Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Use this command to start pre-training a model with a CSV dataset. Adjust NUM_GPUS, file paths, and training parameters as needed. For multi-machine training, include additional torchrun arguments. ```bash torchrun --standalone --nproc_per_node=NUM_GPUS \ -m unimol_tools.cli.run_pretrain \ dataset.train_path=train.csv \ dataset.valid_path=valid.csv \ dataset.data_type=csv \ dataset.smiles_column=smiles \ training.total_steps=10000 \ training.batch_size=16 \ training.update_freq=1 ``` -------------------------------- ### Get Pretrained Model Paths Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Retrieves the file paths for the all-hydrogen and no-hydrogen pretrained Uni-Mol models. Use these paths when loading tokenizers and models. ```python from importlib.resources import files all_h_pretrained = files("unimol_hf").joinpath("pretrained/unimol-v1-allh") no_h_pretrained = files("unimol_hf").joinpath("pretrained/unimol-v1-noh") ``` -------------------------------- ### Regression Task with CSV File Path Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md This example demonstrates regression tasks using a CSV file path as input. Customize column names for SMILES and target using `smiles_col` and `target_cols`. Ensure the CSV contains the specified columns. ```Python from unimol_tools import MolTrain, MolPredict # Load the dataset train_data_path = '../datasets/ESol/train_data.csv' test_data_path = '../datasets/ESol/test_data.csv' reg = MolTrain(task='regression', data_type='molecule', epochs=20, batch_size=32, metrics='mae', smiles_col='smiles', target_cols=['ESOL predicted log solubility in mols per litre'], save_path='./exp_esol', ) reg.fit(train_data_path) predictor = MolPredict(load_model='./exp_esol') y_pred = predictor.predict(data=test_data_path) ``` -------------------------------- ### Get Molecular Representations Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Extracts the CLS token representation for a batch of SMILES strings using a pretrained Uni-Mol model. The output shape is (batch_size, hidden_size). ```python from importlib.resources import files import torch import unimol_hf from transformers import AutoModel, AutoTokenizer from unimol_hf import UnimolDataCollator pretrained = files("unimol_hf").joinpath("pretrained/unimol-v1-allh") smiles = ["CCO", "c1ccccc1"] tokenizer = AutoTokenizer.from_pretrained(str(pretrained)) model = AutoModel.from_pretrained(str(pretrained)).eval() collator = UnimolDataCollator(pad_token_id=tokenizer.pad_token_id) batch = collator([tokenizer.encode(smi) for smi in smiles]) with torch.no_grad(): cls_repr = model.get_cls_repr(**batch) print(cls_repr.shape) # torch.Size([2, 512]) ``` -------------------------------- ### Common RuntimeError in Multiprocessing Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md This error occurs when multiprocessing code is not properly guarded with `if __name__ == '__main__':`. It indicates a failure to start child processes correctly. ```python RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable. ``` -------------------------------- ### Python Multiprocessing Idiom Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Use `if __name__ == '__main__':` to enclose multiprocessing code. This prevents code re-execution in child processes, avoiding common errors like `RuntimeError: An attempt has been made to start a new process...`. ```python if __name__ == '__main__': freeze_support() ... ``` -------------------------------- ### Pretrain Uni-Mol from Scratch using LMDB Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Pretrain Uni-Mol models from scratch using LMDB datasets. Configure training paths, data type, dictionary path, total steps, batch size, and update frequency. The effective batch size depends on the number of GPUs. ```bash torchrun --standalone --nproc_per_node=NUM_GPUS \ -m unimol_tools.cli.run_pretrain \ dataset.train_path=train.lmdb \ dataset.valid_path=valid.lmdb \ dataset.data_type=lmdb \ dataset.dict_path=dict.txt \ training.total_steps=10000 \ training.batch_size=16 \ training.update_freq=1 ``` -------------------------------- ### Continue Training a Model Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Initialize a MolTrain object, fit it to your training data, and then create a second MolTrain object with `load_model_dir` pointing to the previous model's save path to continue training. ```python clf = MolTrain( task='regression', data_type='molecule', epochs=10, batch_size=16, save_path='./model_dir', remove_hs=False, target_cols='TARGET', ) pred = clf.fit(data = train_data) # After train a model, set load_model_dir='./model_dir' to continue training clf2 = MolTrain( task='regression', data_type='molecule', epochs=10, batch_size=16, save_path='./retrain_model_dir', remove_hs=False, target_cols='TARGET', load_model_dir='./model_dir', ) pred2 = clf.fit(data = retrain_data) ``` -------------------------------- ### Pretrain Model on CSV Dataset via CLI Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Pretrain Uni-Mol models using a CSV dataset. Environment variables for distributed training and Hydra configuration are set. The effective batch size depends on GPU count, batch size, and update frequency. ```bash export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 export HYDRA_FULL_ERROR=1 export OMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=NUM_GPUS \ -m unimol_tools.cli.run_pretrain \ dataset.train_path=train.csv \ dataset.valid_path=valid.csv \ dataset.data_type=csv \ dataset.smiles_column=smiles \ training.total_steps=1000000 \ training.batch_size=16 \ training.update_freq=1 ``` -------------------------------- ### Train a Model via CLI Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Use this command to train a model. Specify training data, task type, save path, relevant columns, and training hyperparameters. ```bash python -m unimol_tools.cli.run_train \ train_path=train.csv \ task=regression \ save_path=./exp \ smiles_col=smiles \ target_cols=[target1] \ epochs=10 \ learning_rate=1e-4 \ batch_size=16 \ kfold=5 ``` -------------------------------- ### Enable DDP for Training Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Initialize the MolTrain class with `use_ddp=True` and specify the GPUs to use with `use_gpu`. This enables Distributed Data Parallel for faster training. ```python from unimol_tools import MolTrain # Initialize the training class with DDP enabled if __name__ == '__main__': clf = MolTrain( task='regression', data_type='molecule', epochs=10, batch_size=16, save_path='./model_dir', remove_hs=False, target_cols='TARGET', use_ddp=True, use_gpu="all" ) pred = clf.fit(data = train_data) ``` -------------------------------- ### Pretrain Model on LMDB Dataset via CLI Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Pretrain Uni-Mol models using an LMDB dataset. Environment variables for distributed training and Hydra configuration are set. The effective batch size depends on GPU count, batch size, and update frequency. ```bash export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 export HYDRA_FULL_ERROR=1 export OMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=NUM_GPUS \ -m unimol_tools.cli.run_pretrain \ dataset.train_path=train.lmdb \ dataset.valid_path=valid.lmdb \ dataset.data_type=lmdb \ dataset.dict_path=dict.txt \ training.total_steps=1000000 \ training.batch_size=16 \ training.update_freq=1 ``` -------------------------------- ### Configure Hugging Face Mirror Endpoint Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/installation.md Set the HF_ENDPOINT environment variable to use a mirror for faster model downloads if the official endpoint is slow. ```bash export HF_ENDPOINT=https://hf-mirror.com ``` -------------------------------- ### Set Custom Directory for Pre-trained Weights Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Specifies a custom directory for pre-trained weights using the UNIMOL_WEIGHT_DIR environment variable. This is useful if weights have been downloaded from a source other than the automatic Hugging Face download. ```bash export UNIMOL_WEIGHT_DIR=/path/to/your/weights/dir/ ``` -------------------------------- ### Train and Predict with Dictionary Data Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Prepare data as a dictionary, split into training and testing sets, train a multilabel regression model, and make predictions. ```python from unimol_tools import MolTrain, MolPredict import pandas as pd import numpy as np # Load the dataset df = pd.read_csv('../datasets/FreeSolv/SAMPL.csv') data_dict = { 'SMILES': df['smiles'].tolist(), 'target': [df['expt'].tolist(), df['calc'].tolist()] } # Divide the training set and test set num_molecules = len(data_dict['SMILES']) np.random.seed(42) indices = np.random.permutation(num_molecules) train_end = int(0.8 * num_molecules) train_val_idx = indices[:train_end] test_idx = indices[train_end:] train_val_dict = { 'SMILES': [data_dict['SMILES'][i] for i in train_val_idx], 'target': [data_dict['target'][0][i] for i in train_val_idx], } test_dict = { 'SMILES': [data_dict['SMILES'][i] for i in test_idx], 'target': [data_dict['target'][0][i] for i in test_idx], } mreg = MolTrain(task='multilabel_regression', data_type='molecule', epochs=20, batch_size=32, metrics='mae', save_path='./exp_dict', ) mreg.fit(train_val_dict) predictor = MolPredict(load_model='./exp_dict') y_pred = predictor.predict(data=test_dict) ``` -------------------------------- ### Predict with a Trained Model via CLI Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Use this command for prediction. Provide the path to the trained model and the data path for prediction. ```bash python -m unimol_tools.cli.run_predict load_model=./exp data_path=test.csv ``` -------------------------------- ### Enable DDP for Molecular Representation Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Initialize UniMolRepr with `use_ddp=True` and specify GPUs. Note: DDP is not recommended for small datasets due to communication overhead. ```python from unimol_tools import UniMolRepr # Initialize the UniMolRepr class with DDP enabled if __name__ == '__main__': repr_model = UniMolRepr( data_type='molecule', batch_size=32, remove_hs=False, model_name='unimolv2', model_size='84m', use_ddp=True, # Enable Distributed Data Parallel use_gpu='0,1' # Use GPU 0 and 1 ) unimol_repr = repr_model.get_repr(smiles_list, return_atomic_reprs=True) # CLS token representation print(unimol_repr['cls_repr']) # Atomic-level representation print(unimol_repr['atomic_reprs']) ``` -------------------------------- ### Regression Training with Trainer Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Trains a Uni-Mol model for regression using Hugging Face Trainer. Ensure your training data has 'SMILES' and 'TARGET' columns. The model and tokenizer are saved to './hf_reg_exp'. ```python from importlib.resources import files import pandas as pd import unimol_hf from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments from unimol_hf import UnimolConfig, UnimolDataCollator, UnimolSmilesDataset pretrained = files("unimol_hf").joinpath("pretrained/unimol-v1-allh") train_data = pd.read_csv("train.csv") # columns: SMILES, TARGET tokenizer = AutoTokenizer.from_pretrained(str(pretrained)) config = UnimolConfig.from_pretrained( str(pretrained), num_labels=1, problem_type="regression", ) model = AutoModelForSequenceClassification.from_pretrained(str(pretrained), config=config) train_dataset = UnimolSmilesDataset( train_data, tokenizer, smiles_col="SMILES", target_col="TARGET", problem_type="regression", ) collator = UnimolDataCollator( pad_token_id=tokenizer.pad_token_id, problem_type="regression", ) args = TrainingArguments( output_dir="./hf_reg_exp", per_device_train_batch_size=16, num_train_epochs=10, learning_rate=1e-4, remove_unused_columns=False, report_to=[], ) trainer = Trainer( model=model, args=args, train_dataset=train_dataset, data_collator=collator, ) trainer.train() model.save_pretrained("./hf_reg_exp") tokenizer.save_pretrained("./hf_reg_exp") ``` -------------------------------- ### Classification Training with Trainer Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Trains a Uni-Mol model for single-label classification using Hugging Face Trainer. Ensure your training data has 'SMILES' and 'TARGET' columns. The model and tokenizer are saved to './hf_cls_exp'. ```python from importlib.resources import files import pandas as pd import unimol_hf # register Uni-Mol Auto classes from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments from unimol_hf import UnimolConfig, UnimolDataCollator, UnimolSmilesDataset pretrained = files("unimol_hf").joinpath("pretrained/unimol-v1-allh") train_data = pd.read_csv("train.csv") # columns: SMILES, TARGET tokenizer = AutoTokenizer.from_pretrained(str(pretrained)) config = UnimolConfig.from_pretrained( str(pretrained), num_labels=2, problem_type="single_label_classification", ) model = AutoModelForSequenceClassification.from_pretrained(str(pretrained), config=config) train_dataset = UnimolSmilesDataset( train_data, tokenizer, smiles_col="SMILES", target_col="TARGET", problem_type="single_label_classification", ) collator = UnimolDataCollator( pad_token_id=tokenizer.pad_token_id, problem_type="single_label_classification", ) args = TrainingArguments( output_dir="./hf_cls_exp", per_device_train_batch_size=16, num_train_epochs=10, learning_rate=1e-4, remove_unused_columns=False, report_to=[], ) trainer = Trainer( model=model, args=args, train_dataset=train_dataset, data_collator=collator, ) trainer.train() model.save_pretrained("./hf_cls_exp") tokenizer.save_pretrained("./hf_cls_exp") ``` -------------------------------- ### Set Hugging Face Mirror Endpoint Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Configures the environment variable HF_ENDPOINT to use a mirror for downloading models if the default endpoint is slow or fails. The toolkit automatically retries with this mirror if the default fails and HF_ENDPOINT is not set. ```bash export HF_ENDPOINT=https://hf-mirror.com ``` -------------------------------- ### Train and Predict with Specific Target Columns Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Train a multilabel regression model using a dictionary with specific target columns and save predictions to a specified path. ```python from unimol_tools import MolTrain, MolPredict import pandas as pd import numpy as np # Load the dataset df = pd.read_csv('../datasets/FreeSolv/SAMPL.csv') data_dict = { 'SMILES': df['smiles'].tolist(), 'expt': df['expt'].tolist(), 'calc': df['calc'].tolist() } # Divide the training set and test set num_molecules = len(data_dict['SMILES']) np.random.seed(42) indices = np.random.permutation(num_molecules) train_end = int(0.8 * num_molecules) train_val_idx = indices[:train_end] test_idx = indices[train_end:] train_val_dict = { 'SMILES': [data_dict['SMILES'][i] for i in train_val_idx], 'expt': [data_dict['expt'][i] for i in train_val_idx], 'calc': [data_dict['calc'][i] for i in train_val_idx], } test_dict = { 'SMILES': [data_dict['SMILES'][i] for i in test_idx], 'expt': [data_dict['expt'][i] for i in test_idx], 'calc': [data_dict['calc'][i] for i in test_idx], } mreg = MolTrain(task='multilabel_regression', data_type='molecule', epochs=20, batch_size=32, metrics='mae', target_cols=['expt', 'calc'], save_path='./exp_dict', ) mreg.fit(train_val_dict) predictor = MolPredict(load_model='./exp_dict') y_pred = predictor.predict(data=test_dict, save_path='./pre_dict') ``` -------------------------------- ### Train and Predict Molecules with UniMol Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Use MolTrain to train a classification or regression model on molecular data and MolPredict to make predictions with a loaded model. Ensure data is in a compatible format like CSV. ```python from unimol_tools import MolTrain, MolPredict clf = MolTrain(task='classification', data_type='molecule', epochs=10, batch_size=16, metrics='auc', model_name='unimolv1', # avaliable: unimolv1, unimolv2 model_size='84m', # work when model_name is unimolv2. avaliable: 84m, 164m, 310m, 570m, 1.1B. ) pred = clf.fit(data = train_data) # currently support data with smiles based csv/txt file clf = MolPredict(load_model='../exp') res = clf.predict(data = test_data) ``` -------------------------------- ### Train Multilabel Regression Model with CSV Data Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Train a multilabel regression model using a CSV file. Specify target columns and save the trained model. ```python data_path = '../datasets/FreeSolv/SAMPL.csv' mreg = MolTrain(task='multilabel_regression', data_type='molecule', epochs=20, batch_size=32, metrics='mae', smiles_col='smiles', target_cols='expt,calc', save_path='./exp_csv', ) mreg.fit(data_path) ``` -------------------------------- ### Molecule Property Prediction with MolTrain Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Use MolTrain for classification tasks on molecular data. Pretrained models are downloaded automatically if not specified. Supports data in SMILES-based CSV/TXT, SDF, or a custom dictionary format. ```python from unimol_tools import MolTrain, MolPredict clf = MolTrain( task='classification', data_type='molecule', epochs=10, batch_size=16, metrics='auc', # pretrained weights are downloaded automatically when left as ``None`` # pretrained_model_path='/path/to/checkpoint.ckpt', # pretrained_dict_path='/path/to/dict.txt', ) clf.fit(data = train_data) # currently support data with smiles based csv/txt file, and sdf file with mol, # and custom dict of {'atoms':[['C','C'],['C','H','O']], 'coordinates':[coordinates_1,coordinates_2]} # The dict format can refer to the following format, or be obtained from sdf, # which can also be directly input into the model. train_sdf = PandasTools.LoadSDF('exp/unimol_conformers_train.sdf') train_dict = { 'atoms': [list(atom.GetSymbol() for atom in mol.GetAtoms()) for mol in train_sdf['ROMol']], # atoms[0]: ['C', 'C', 'O', 'C', 'O', 'C', ...] 'coordinates': [mol.GetConformers()[0].GetPositions() for mol in train_sdf['ROMol']], # coordinates[0]: array([[ 6.6462, -1.8268, 1.9275], # [ 6.1552, -1.9367, 0.4873], # [ 5.1832, -0.8757, 0.3007], # [ 5.4651, -0.0272, -0.7266], # [ 4.8586, -0.0844, -1.7917], # [ 6.5362, 0.9767, -0.3742], # ...,]) 'TARGET': train_sdf['TARGET'].tolist() # TARGET: [0, 1, 0, 0, 1, 0, ...] } # clf.fit(data = train_sdf) # clf.fit(data = train_dict) clf = MolPredict(load_model='../exp') res = clf.predict(data = test_data) ``` -------------------------------- ### Molecule Representation with UniMolRepr Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Generate molecular representations using UniMolRepr. By default, it fetches pretrained models from Hugging Face. It can return both the CLS token representation and atomic-level representations. ```python import numpy as np from unimol_tools import UniMolRepr # single SMILES UniMol representation. If no paths are provided the # pretrained model and dictionary are fetched from Hugging Face. clf = UniMolRepr( data_type='molecule', remove_hs=False, # pretrained_model_path='/path/to/checkpoint.ckpt', # pretrained_dict_path='/path/to/dict.txt', ) smiles = 'c1ccc(cc1)C2=NCC(=O)Nc3c2cc(cc3)[N+](=O)[O]' smiles_list = [smiles] unimol_repr = clf.get_repr(smiles_list, return_atomic_reprs=True) # CLS token repr print(np.array(unimol_repr['cls_repr']).shape) # atomic level repr, align with rdkit mol.GetAtoms() print(np.array(unimol_repr['atomic_reprs']).shape) ``` -------------------------------- ### Generate Molecular Representations via CLI Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md Use this command to generate molecular representations. Specify the data path and the column containing SMILES strings. ```bash python -m unimol_tools.cli.run_repr data_path=test.csv smiles_col=smiles ``` -------------------------------- ### Multilabel Classification Training with SDF Data Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Trains a multilabel classification model using molecular data loaded directly from an SDF file. Fills missing values in specified target columns with 0. ```python from unimol_tools import MolTrain, MolPredict from rdkit.Chem import PandasTools # Load the dataset data_path = '../datasets/tox21.sdf' data = PandasTools.LoadSDF(data_path) # Fill missing values ​​with 0 data['SR-HSE'] = data['SR-HSE'].fillna(0) data['NR-AR'] = data['NR-AR'].fillna(0) mlclf = MolTrain(task='multilabel_classification', data_type='molecule', epochs=20, batch_size=32, metrics='auc', target_cols=['SR-HSE', 'NR-AR'], save_path='./exp_sdf', ) mlclf.fit(data) ``` -------------------------------- ### Generate Molecular and Atomic Representations Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Obtain Uni-Mol representations for molecules or pockets. For molecules, provide SMILES strings. For pockets, provide a dictionary with atoms, coordinates, and optional residue information. Ensure pocket atom count does not exceed 256. ```python import numpy as np from unimol_tools import UniMolRepr # single smiles unimol representation clf = UniMolRepr(data_type='molecule', # avaliable: molecule, oled, pocket. Only for unimolv1. remove_hs=False, model_name='unimolv1', # avaliable: unimolv1, unimolv2 model_size='84m', # work when model_name is unimolv2. avaliable: 84m, 164m, 310m, 570m, 1.1B. ) smiles = 'c1ccc(cc1)C2=NCC(=O)Nc3c2cc(cc3)[N+](=O)[O]' smiles_list = [smiles] unimol_repr = clf.get_repr(smiles_list, return_atomic_reprs=True) # CLS token repr print(np.array(unimol_repr['cls_repr']).shape) # atomic level repr, align with rdkit mol.GetAtoms() print(np.array(unimol_repr['atomic_reprs']).shape) # For the pocket, please select and extract the atoms nearby; the total number of atoms should preferably not exceed 256. clf = UniMolRepr(data_type='pocket', remove_hs=False, ) pocket_dict = { 'atoms': atoms, 'coordinates': coordinates, 'residue': residue, # Optional } unimol_repr = clf.get_repr(pocket_dict, return_atomic_reprs=True) ``` -------------------------------- ### Multilabel Classification Training with CSV Data Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Trains a multilabel classification model using molecular data from a CSV file. Handles missing values by filling them with 0 and specifies target columns. ```python import pandas as pd from unimol_tools import MolTrain, MolPredict # Load the dataset df = pd.read_csv('../datasets/tox21.csv') # Fill missing values ​​with 0 df.fillna(0, inplace=True) df.drop(columns=['mol_id'], inplace=True) # Divide the training set and test set train_df = df.sample(frac=0.8, random_state=42) test_df = df.drop(train_df.index) train_df_dict = train_df.to_dict(orient='list') test_df_dict = test_df.to_dict(orient='list') mlclf = MolTrain(task='multilabel_classification', data_type='molecule', epochs=20, batch_size=32, metrics='auc', smiles_col='smiles', target_cols=[col for col in df.columns if col != 'smiles'], ) mlclf.fit(train_df_dict) predictor = MolPredict(load_model='./exp') pred = predictor.predict(test_df_dict['smiles']) ``` -------------------------------- ### Molecule Regression Training and Prediction Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Trains a regression model on molecular data and predicts properties for a test set. Requires pre-split data with SMILES, atoms, coordinates, and targets. ```python num_molecules = len(valid_smiles) np.random.seed(42) indices = np.random.permutation(num_molecules) train_end = int(0.8 * num_molecules) train_val_idx = indices[:train_end] test_idx = indices[train_end:] train_val_smiles = [valid_smiles[i] for i in train_val_idx] test_smiles = [valid_smiles[i] for i in test_idx] train_val_atoms = [valid_atoms[i] for i in train_val_idx] test_atoms = [valid_atoms[i] for i in test_idx] train_val_coordinates = [valid_coordinates[i] for i in train_val_idx] test_coordinates = [valid_coordinates[i] for i in test_idx] train_val_targets = [valid_targets[i] for i in train_val_idx] test_targets = [valid_targets[i] for i in test_idx] train_val_data = { 'target': train_val_targets, 'atoms': train_val_atoms, 'coordinates': train_val_coordinates, 'SMILES': train_val_smiles, } test_data = { 'SMILES': test_smiles, 'atoms': test_atoms, 'coordinates': test_coordinates, } reg = MolTrain(task='regression', data_type='molecule', epochs=20, batch_size=32, metrics='mae', save_path='./exp', ) reg.fit(train_val_data) predictor = MolPredict(load_model='./exp') y_pred = predictor.predict(data=test_data, save_path='./pre') # Specify save_path to store prediction results ``` -------------------------------- ### Citation for Uni-QSAR Source: https://github.com/deepmodeling/unimol_tools/blob/main/README.md This is a BibTeX entry for the Uni-QSAR paper, which should be cited when using the Uni-Mol tools. ```bibtex @article{gao2023uni, title={Uni-qsar: an auto-ml tool for molecular property prediction}, author={Gao, Zhifeng and Ji, Xiaohong and Zhao, Guojiang and Wang, Hongshuai and Zheng, Hang and Ke, Guolin and Zhang, Linfeng}, journal={arXiv preprint arXiv:2304.12239}, year={2023} } ``` -------------------------------- ### Regression Task with Atoms and Coordinates Input Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Use this snippet for regression tasks when providing data as lists of atoms and coordinates. SMILES are optional but required for scaffold-based grouping. Supports atom types or atomic numbers. ```Python import numpy as np from unimol_tools import MolTrain, MolPredict from rdkit import Chem # Load the dataset data = np.load('../datasets/DMC.npz', allow_pickle=True) atoms_all = data['atoms'] coordinates_all = data['coordinates'] smiles_all = data['graphs'] all_targets = data['Etot'] # Filter illegal smiles data valid_smiles = [] valid_atoms = [] valid_coordinates = [] valid_targets = [] for smiles, target, atoms, coordinates in zip(smiles_all, all_targets, atoms_all, coordinates_all): try: mol = Chem.MolFromSmiles(smiles) if mol is not None: valid_smiles.append(smiles) valid_atoms.append(atoms) valid_coordinates.append(coordinates) valid_targets.append(target) except Exception as e: print(f"Invalid SMILES: {smiles}, Error: {e}") ``` -------------------------------- ### Multiclass Classification Training and Prediction Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Trains a multiclass classification model using molecular data loaded from a CSV file. Filters data based on target values and splits into training and testing sets. ```python import pandas as pd from unimol_tools import MolTrain, MolPredict import numpy as np # Load the dataset df = pd.read_csv('../datasets/ESOL/ESOL.csv') data_dict = { 'SMILES': df['smiles'].tolist(), 'target': df['Number of H-Bond Donors'].tolist() } data_dict['SMILES'] = [smiles for i, smiles in enumerate(data_dict['SMILES']) if data_dict['target'][i] <= 4] data_dict['target'] = [target for target in data_dict['target'] if target <= 4] # Divide the training set and test set num_molecules = len(data_dict['SMILES']) np.random.seed(42) indices = np.random.permutation(num_molecules) train_end = int(0.8 * num_molecules) train_val_idx = indices[:train_end] test_idx = indices[train_end:] train_val_dict = { 'SMILES': [data_dict['SMILES'][i] for i in train_val_idx], 'target': [data_dict['target'][i] for i in train_val_idx], } test_dict = { 'SMILES': [data_dict['SMILES'][i] for i in test_idx], 'target': [data_dict['target'][i] for i in test_idx], } mclf = MolTrain(task='multiclass', data_type='molecule', epochs=20, batch_size=32, metrics='acc', save_path='./exp', ) mclf.fit(train_val_dict) predictor = MolPredict(load_model='./exp') y_pred = predictor.predict(data=test_dict) ``` -------------------------------- ### Classification Task with Pandas DataFrame Source: https://github.com/deepmodeling/unimol_tools/blob/main/docs/source/quickstart.md Use this snippet for classification tasks when your data is in a Pandas DataFrame. Customize column names for SMILES and target using `smiles_col` and `target_cols`. ```Python import pandas as pd from unimol_tools import MolTrain, MolPredict # Load the dataset df = pd.read_csv('../datasets/Ames/Ames.csv') df = df.drop(columns=['CAS_NO']).rename(columns={'Activity': 'target'}) # Divide the training set and test set train_df = df.sample(frac=0.8, random_state=42) test_df = df.drop(train_df.index) train_df_dict = train_df.to_dict(orient='list') test_df_dict = test_df.to_dict(orient='list') clf = MolTrain(task='classification', data_type='molecule', epochs=20, batch_size=16, metrics='auc', smiles_col='Canonical_Smiles', ) clf.fit(train_df_dict) predictor = MolPredict(load_model='./exp') pred = predictor.predict(test_df_dict['Canonical_Smiles']) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.