从零构建DrugBAN模型实战药物-靶点预测全流程解析在药物发现领域准确预测药物分子与靶点蛋白的相互作用DTI能显著降低研发成本。传统实验方法耗时费力而深度学习模型如DrugBAN通过双线性注意力机制不仅能预测结合概率还能可视化关键相互作用位点。本文将带您从SMILES序列和蛋白序列出发完整实现一个可解释的DTI预测系统。1. 环境配置与数据准备1.1 工具链搭建推荐使用Python 3.8和CUDA 11.3环境核心工具包包括conda create -n drugban python3.8 conda install -c rdkit rdkit pip install torch1.12.0cu113 torchvision0.13.0cu113 --extra-index-url https://download.pytorch.org/whl/cu113 pip install biopython pandas scikit-learn注意RDKit对分子结构的处理需要严格校验SMILES格式建议预先使用rdkit.Chem.MolFromSmiles()进行过滤1.2 数据集处理以BindingDB数据集为例原始数据需要转换为模型可读的格式字段名类型说明smitext标准化的SMILES字符串protein_seqtext蛋白质的氨基酸序列labelint1表示结合0表示不结合from Bio.Seq import Seq from rdkit import Chem def validate_sample(smi, seq): try: mol Chem.MolFromSmiles(smi) protein Seq(seq) return mol is not None and len(protein) 50 except: return False2. 分子与蛋白的特征工程2.1 分子图编码采用GCN对SMILES进行编码时需要先转换为分子图import torch from torch_geometric.data import Data def smiles_to_graph(smiles): mol Chem.MolFromSmiles(smiles) atoms mol.GetAtoms() # 原子特征矩阵 x torch.tensor([[atom.GetAtomicNum(), atom.GetDegree(), atom.GetHybridization().real] for atom in atoms], dtypetorch.float) # 边索引 edge_index [] for bond in mol.GetBonds(): i bond.GetBeginAtomIdx() j bond.GetEndAtomIdx() edge_index.extend([[i, j], [j, i]]) return Data(xx, edge_indextorch.tensor(edge_index).t().contiguous())2.2 蛋白序列编码使用CNN处理蛋白序列时建议采用如下嵌入策略将每个氨基酸转换为128维向量添加位置编码捕获序列顺序通过1D卷积提取局部特征class ProteinEncoder(nn.Module): def __init__(self): super().__init__() self.embed nn.Embedding(26, 128) # 25种氨基酸填充符 self.conv nn.Sequential( nn.Conv1d(128, 64, kernel_size3), nn.ReLU(), nn.MaxPool1d(2) ) def forward(self, x): x self.embed(x) # [batch, seq_len, 128] x x.permute(0,2,1) # 通道维度在前 return self.conv(x)3. 双线性注意力网络实现3.1 BAN核心结构双线性注意力通过矩阵运算捕获分子-蛋白相互作用class BANLayer(nn.Module): def __init__(self, mol_dim, prot_dim): super().__init__() self.W nn.Parameter(torch.randn(mol_dim, prot_dim)) def forward(self, mol_feat, prot_feat): # mol_feat: [batch, mol_nodes, mol_dim] # prot_feat: [batch, prot_nodes, prot_dim] attention torch.einsum(bmd,dp,bpn-bmn, mol_feat, self.W, prot_feat.transpose(1,2)) mol_attn torch.softmax(attention.max(2)[0], dim1) prot_attn torch.softmax(attention.max(1)[0], dim1) return mol_attn, prot_attn3.2 可视化注意力机制通过RDKit可直观展示关键原子位点def highlight_atoms(mol, atom_weights): from rdkit.Chem import Draw highlight {i: float(atom_weights[i]) for i in range(mol.GetNumAtoms())} return Draw.MolToImage(mol, highlightAtomshighlight.keys(), highlightAtomColorshighlight)4. 模型训练与调优4.1 对抗训练技巧CDAN模块的实现要点特征提取器需要冻结部分层域分类器采用梯度反转层学习率设置为BAN模块的1/10class GradientReversalFn(torch.autograd.Function): staticmethod def forward(ctx, x, alpha): ctx.alpha alpha return x staticmethod def backward(ctx, grad_output): return -ctx.alpha * grad_output, None class CDAN(nn.Module): def __init__(self, input_dim): super().__init__() self.domain_classifier nn.Sequential( nn.Linear(input_dim, 64), nn.ReLU(), nn.Linear(64, 2) ) def forward(self, feat, alpha1.0): feat GradientReversalFn.apply(feat, alpha) return self.domain_classifier(feat)4.2 多任务损失函数联合优化DTI预测和域适应目标def compute_loss(y_pred, y_true, domain_pred, domain_true): bce_loss nn.BCELoss()(y_pred, y_true) domain_loss nn.CrossEntropyLoss()(domain_pred, domain_true) return bce_loss 0.3 * domain_loss # 平衡系数需网格搜索5. 生产级部署建议实际应用中还需考虑建立分子特征缓存数据库使用TorchScript导出模型开发REST API接口import flask app flask.Flask(__name__) app.route(/predict, methods[POST]) def predict(): smi flask.request.json[smiles] seq flask.request.json[sequence] mol_graph smiles_to_graph(smi) prot_feat protein_encoder(seq) with torch.no_grad(): pred model(mol_graph, prot_feat) return {probability: float(pred)}在真实项目中使用时建议先用小规模数据验证流程再逐步扩展到千万级化合物库。模型解释性结果应与生物学家合作验证这对新靶点发现尤为重要。
用DrugBAN搞定药物-靶点预测:从SMILES序列到蛋白,手把手跑通双线性注意力网络
从零构建DrugBAN模型实战药物-靶点预测全流程解析在药物发现领域准确预测药物分子与靶点蛋白的相互作用DTI能显著降低研发成本。传统实验方法耗时费力而深度学习模型如DrugBAN通过双线性注意力机制不仅能预测结合概率还能可视化关键相互作用位点。本文将带您从SMILES序列和蛋白序列出发完整实现一个可解释的DTI预测系统。1. 环境配置与数据准备1.1 工具链搭建推荐使用Python 3.8和CUDA 11.3环境核心工具包包括conda create -n drugban python3.8 conda install -c rdkit rdkit pip install torch1.12.0cu113 torchvision0.13.0cu113 --extra-index-url https://download.pytorch.org/whl/cu113 pip install biopython pandas scikit-learn注意RDKit对分子结构的处理需要严格校验SMILES格式建议预先使用rdkit.Chem.MolFromSmiles()进行过滤1.2 数据集处理以BindingDB数据集为例原始数据需要转换为模型可读的格式字段名类型说明smitext标准化的SMILES字符串protein_seqtext蛋白质的氨基酸序列labelint1表示结合0表示不结合from Bio.Seq import Seq from rdkit import Chem def validate_sample(smi, seq): try: mol Chem.MolFromSmiles(smi) protein Seq(seq) return mol is not None and len(protein) 50 except: return False2. 分子与蛋白的特征工程2.1 分子图编码采用GCN对SMILES进行编码时需要先转换为分子图import torch from torch_geometric.data import Data def smiles_to_graph(smiles): mol Chem.MolFromSmiles(smiles) atoms mol.GetAtoms() # 原子特征矩阵 x torch.tensor([[atom.GetAtomicNum(), atom.GetDegree(), atom.GetHybridization().real] for atom in atoms], dtypetorch.float) # 边索引 edge_index [] for bond in mol.GetBonds(): i bond.GetBeginAtomIdx() j bond.GetEndAtomIdx() edge_index.extend([[i, j], [j, i]]) return Data(xx, edge_indextorch.tensor(edge_index).t().contiguous())2.2 蛋白序列编码使用CNN处理蛋白序列时建议采用如下嵌入策略将每个氨基酸转换为128维向量添加位置编码捕获序列顺序通过1D卷积提取局部特征class ProteinEncoder(nn.Module): def __init__(self): super().__init__() self.embed nn.Embedding(26, 128) # 25种氨基酸填充符 self.conv nn.Sequential( nn.Conv1d(128, 64, kernel_size3), nn.ReLU(), nn.MaxPool1d(2) ) def forward(self, x): x self.embed(x) # [batch, seq_len, 128] x x.permute(0,2,1) # 通道维度在前 return self.conv(x)3. 双线性注意力网络实现3.1 BAN核心结构双线性注意力通过矩阵运算捕获分子-蛋白相互作用class BANLayer(nn.Module): def __init__(self, mol_dim, prot_dim): super().__init__() self.W nn.Parameter(torch.randn(mol_dim, prot_dim)) def forward(self, mol_feat, prot_feat): # mol_feat: [batch, mol_nodes, mol_dim] # prot_feat: [batch, prot_nodes, prot_dim] attention torch.einsum(bmd,dp,bpn-bmn, mol_feat, self.W, prot_feat.transpose(1,2)) mol_attn torch.softmax(attention.max(2)[0], dim1) prot_attn torch.softmax(attention.max(1)[0], dim1) return mol_attn, prot_attn3.2 可视化注意力机制通过RDKit可直观展示关键原子位点def highlight_atoms(mol, atom_weights): from rdkit.Chem import Draw highlight {i: float(atom_weights[i]) for i in range(mol.GetNumAtoms())} return Draw.MolToImage(mol, highlightAtomshighlight.keys(), highlightAtomColorshighlight)4. 模型训练与调优4.1 对抗训练技巧CDAN模块的实现要点特征提取器需要冻结部分层域分类器采用梯度反转层学习率设置为BAN模块的1/10class GradientReversalFn(torch.autograd.Function): staticmethod def forward(ctx, x, alpha): ctx.alpha alpha return x staticmethod def backward(ctx, grad_output): return -ctx.alpha * grad_output, None class CDAN(nn.Module): def __init__(self, input_dim): super().__init__() self.domain_classifier nn.Sequential( nn.Linear(input_dim, 64), nn.ReLU(), nn.Linear(64, 2) ) def forward(self, feat, alpha1.0): feat GradientReversalFn.apply(feat, alpha) return self.domain_classifier(feat)4.2 多任务损失函数联合优化DTI预测和域适应目标def compute_loss(y_pred, y_true, domain_pred, domain_true): bce_loss nn.BCELoss()(y_pred, y_true) domain_loss nn.CrossEntropyLoss()(domain_pred, domain_true) return bce_loss 0.3 * domain_loss # 平衡系数需网格搜索5. 生产级部署建议实际应用中还需考虑建立分子特征缓存数据库使用TorchScript导出模型开发REST API接口import flask app flask.Flask(__name__) app.route(/predict, methods[POST]) def predict(): smi flask.request.json[smiles] seq flask.request.json[sequence] mol_graph smiles_to_graph(smi) prot_feat protein_encoder(seq) with torch.no_grad(): pred model(mol_graph, prot_feat) return {probability: float(pred)}在真实项目中使用时建议先用小规模数据验证流程再逐步扩展到千万级化合物库。模型解释性结果应与生物学家合作验证这对新靶点发现尤为重要。