Upload 7 files
Browse files- model/dataset.py +130 -0
- model/help.md +22 -0
- model/hyperparameters.json +129 -0
- model/main.py +60 -0
- model/model.py +277 -0
- model/python_version.txt +1 -0
- model/requirements.txt +9 -0
model/dataset.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from rdkit import Chem
|
| 14 |
+
_RDKIT_AVAILABLE = True
|
| 15 |
+
except ImportError:
|
| 16 |
+
_RDKIT_AVAILABLE = False
|
| 17 |
+
|
| 18 |
+
# Importa BaseDataset de ../base_dataset.py
|
| 19 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 20 |
+
from base_dataset import BaseDataset # noqa: E402
|
| 21 |
+
|
| 22 |
+
# Vocabulário padrão de caracteres SMILES (índice 0 reservado para PAD, 1 para UNK)
|
| 23 |
+
SMILES_CHARS = " ^#%()+-./0123456789=@ABCDEFGHIKLMNOPRSTVXYZ[\\]abcdefgilmnoprstuy$"
|
| 24 |
+
CHAR_TO_IDX = {ch: idx + 2 for idx, ch in enumerate(SMILES_CHARS)}
|
| 25 |
+
VOCAB_SIZE = len(SMILES_CHARS) + 2
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def tokenize_smiles(smiles_list: List[str], max_len: int = 120) -> np.ndarray:
|
| 29 |
+
"""Converte uma lista de strings SMILES em uma matriz de índices inteiros."""
|
| 30 |
+
arr = np.zeros((len(smiles_list), max_len), dtype=np.int64)
|
| 31 |
+
for i, smi in enumerate(smiles_list):
|
| 32 |
+
smi_str = str(smi).strip()
|
| 33 |
+
for j, ch in enumerate(smi_str[:max_len]):
|
| 34 |
+
arr[i, j] = CHAR_TO_IDX.get(ch, 1) # 1 = token desconhecido (UNK)
|
| 35 |
+
return arr
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def augment_smiles(smiles: str, n_aug: int) -> List[str]:
|
| 39 |
+
"""Gera variantes não-canônicas de um SMILES usando RDKit."""
|
| 40 |
+
if not _RDKIT_AVAILABLE or n_aug <= 1:
|
| 41 |
+
return [smiles]
|
| 42 |
+
mol = Chem.MolFromSmiles(str(smiles))
|
| 43 |
+
if mol is None:
|
| 44 |
+
return [smiles]
|
| 45 |
+
variants = [Chem.MolToSmiles(mol, canonical=True)]
|
| 46 |
+
for _ in range(n_aug - 1):
|
| 47 |
+
variants.append(Chem.MolToSmiles(mol, doRandom=True))
|
| 48 |
+
return variants
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class TrainingDataset(BaseDataset):
|
| 52 |
+
"""Dataset de sequências SMILES para o modelo Transformer-CNN."""
|
| 53 |
+
|
| 54 |
+
def _find_smiles_column(self) -> str:
|
| 55 |
+
explicit = self.metadata.get("features")
|
| 56 |
+
if explicit and len(explicit) > 0:
|
| 57 |
+
col = explicit[0]
|
| 58 |
+
if col not in self.df.columns:
|
| 59 |
+
raise ValueError(f"Coluna '{col}' não encontrada no DataFrame.")
|
| 60 |
+
return col
|
| 61 |
+
|
| 62 |
+
for col in self.df.columns:
|
| 63 |
+
if "smiles" in col.lower():
|
| 64 |
+
return col
|
| 65 |
+
|
| 66 |
+
raise ValueError(
|
| 67 |
+
"Nenhuma coluna SMILES encontrada. Defina-a em metadata['features']."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def build_features(self) -> None:
|
| 71 |
+
if self.df is None:
|
| 72 |
+
raise RuntimeError("self.df está vazio; load_raw_data() não rodou.")
|
| 73 |
+
|
| 74 |
+
hp = self.train_config.get("hyperparameters", {}) if self.train_config else {}
|
| 75 |
+
self.max_seq_len = int(hp.get("max_seq_len", 120))
|
| 76 |
+
|
| 77 |
+
smiles_col = self._find_smiles_column()
|
| 78 |
+
self.raw_smiles = self.df[smiles_col].astype(str).tolist()
|
| 79 |
+
|
| 80 |
+
# Mantém self.feature_columns com tamanho = max_seq_len para que
|
| 81 |
+
# dataset.get_num_features() passe o tamanho correto ao create_model
|
| 82 |
+
self.feature_columns = [f"token_{i}" for i in range(self.max_seq_len)]
|
| 83 |
+
self.X = tokenize_smiles(self.raw_smiles, max_len=self.max_seq_len)
|
| 84 |
+
|
| 85 |
+
def get_data_loader(
|
| 86 |
+
self,
|
| 87 |
+
batch_size: int = 32,
|
| 88 |
+
train_ratio: Optional[float] = None,
|
| 89 |
+
seed: Optional[int] = None,
|
| 90 |
+
) -> Tuple[DataLoader, DataLoader]:
|
| 91 |
+
train_ratio, seed = self._resolve_split_params(train_ratio, seed)
|
| 92 |
+
idx_train, idx_val = self._split_indices(train_ratio, seed)
|
| 93 |
+
|
| 94 |
+
assert self.X is not None and self.y is not None
|
| 95 |
+
|
| 96 |
+
hp = self.train_config.get("hyperparameters", {}) if self.train_config else {}
|
| 97 |
+
n_aug = int(hp.get("n_augmentations", 1))
|
| 98 |
+
|
| 99 |
+
# Aplica Data Augmentation apenas nos dados de treino
|
| 100 |
+
if n_aug > 1 and _RDKIT_AVAILABLE:
|
| 101 |
+
aug_smiles: List[str] = []
|
| 102 |
+
aug_y: List[int] = []
|
| 103 |
+
for idx in idx_train:
|
| 104 |
+
variants = augment_smiles(self.raw_smiles[idx], n_aug)
|
| 105 |
+
aug_smiles.extend(variants)
|
| 106 |
+
aug_y.extend([int(self.y[idx])] * len(variants))
|
| 107 |
+
X_train_np = tokenize_smiles(aug_smiles, max_len=self.max_seq_len)
|
| 108 |
+
y_train_np = np.array(aug_y, dtype=np.int64)
|
| 109 |
+
else:
|
| 110 |
+
X_train_np = self.X[idx_train]
|
| 111 |
+
y_train_np = self.y[idx_train]
|
| 112 |
+
|
| 113 |
+
X_train = torch.from_numpy(X_train_np).long()
|
| 114 |
+
y_train = torch.from_numpy(y_train_np).long()
|
| 115 |
+
X_val = torch.from_numpy(self.X[idx_val]).long()
|
| 116 |
+
y_val = torch.from_numpy(self.y[idx_val]).long()
|
| 117 |
+
|
| 118 |
+
bs = self._resolve_batch_size(batch_size)
|
| 119 |
+
train_loader = DataLoader(
|
| 120 |
+
TensorDataset(X_train, y_train), batch_size=bs, shuffle=True
|
| 121 |
+
)
|
| 122 |
+
val_loader = DataLoader(
|
| 123 |
+
TensorDataset(X_val, y_val), batch_size=bs, shuffle=False
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
print(
|
| 127 |
+
f" - Train samples: {len(X_train)} (aug={n_aug}x) | Val samples: {len(X_val)}"
|
| 128 |
+
f" | Batch size: {bs}"
|
| 129 |
+
)
|
| 130 |
+
return train_loader, val_loader
|
model/help.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Transformer-CNN for QSAR/QSPR Modeling
|
| 2 |
+
|
| 3 |
+
## Resume
|
| 4 |
+
Transformer-CNN is a hybrid deep learning architecture designed for chemical property prediction directly from SMILES strings. It combines a Transformer encoder to generate rich contextual character embeddings with a 1D Convolutional Neural Network (CharNN) to extract local chemical motifs.
|
| 5 |
+
|
| 6 |
+
### Common Use Cases:
|
| 7 |
+
* **Antimicrobial Activity Prediction (MIC90/MIC50):** Classifying molecules into active or inactive compounds.
|
| 8 |
+
* **ADMET & Toxicity Profiling:** Predicting mutagenicity, solubility, and pharmacokinetic properties.
|
| 9 |
+
* **Virtual Screening:** Rapidly scoring compound libraries directly from SMILES without pre-computing molecular descriptors.
|
| 10 |
+
|
| 11 |
+
## Content
|
| 12 |
+
|
| 13 |
+
### 1. Core Architecture
|
| 14 |
+
The model processes tokenized SMILES strings through two sequential stages:
|
| 15 |
+
* **Transformer Encoder:** Applies multi-head self-attention across the SMILES sequence to capture long-range dependencies (such as ring closures and branching).
|
| 16 |
+
* **1D Convolutional Block (CharNN):** Applies parallel convolutional filters of varying kernel sizes followed by global max-pooling to detect functional groups and substructures.
|
| 17 |
+
|
| 18 |
+
### 2. SMILES Data Augmentation
|
| 19 |
+
Using RDKit, a single molecule can be represented by multiple valid non-canonical SMILES strings. Generating multiple random SMILES per compound during training acts as a powerful regularization technique for small datasets.
|
| 20 |
+
|
| 21 |
+
### References
|
| 22 |
+
* Karpov, P., Godin, G., & Tetko, I. V. (2020). *Transformer-CNN: Swiss knife for QSAR modeling and interpretation*. Journal of Cheminformatics.
|
model/hyperparameters.json
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"setting": {
|
| 3 |
+
"name": {
|
| 4 |
+
"text": "Nome do modelo",
|
| 5 |
+
"value": "transformer_cnn",
|
| 6 |
+
"Help": "Identificação do modelo Transformer-CNN para SMILES.",
|
| 7 |
+
"default": "transformer_cnn",
|
| 8 |
+
"type": "string",
|
| 9 |
+
"required": true
|
| 10 |
+
},
|
| 11 |
+
"architecture": {
|
| 12 |
+
"text": "Arquitetura do modelo",
|
| 13 |
+
"value": "Transformer-CNN",
|
| 14 |
+
"Help": "Codificador Transformer seguido de CNN 1D (CharNN) para strings SMILES.",
|
| 15 |
+
"default": "Transformer-CNN",
|
| 16 |
+
"type": "string",
|
| 17 |
+
"required": true
|
| 18 |
+
},
|
| 19 |
+
"tipo": {
|
| 20 |
+
"text": "Tipo do modelo",
|
| 21 |
+
"value": "classification",
|
| 22 |
+
"Help": "Define o tipo de tarefa do modelo.",
|
| 23 |
+
"default": "classification",
|
| 24 |
+
"type": "string",
|
| 25 |
+
"required": true
|
| 26 |
+
},
|
| 27 |
+
"learning_type": {
|
| 28 |
+
"text": "Tipo de aprendizado",
|
| 29 |
+
"value": "deep_learning",
|
| 30 |
+
"Help": "Indica se o modelo é de machine learning clássico ou deep learning.",
|
| 31 |
+
"default": "deep_learning",
|
| 32 |
+
"type": "string",
|
| 33 |
+
"required": true
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"train": {
|
| 37 |
+
"batch_size": {
|
| 38 |
+
"text": "Tamanho do batch",
|
| 39 |
+
"Help": "Tamanho do batch usado durante o treinamento.",
|
| 40 |
+
"default": 32,
|
| 41 |
+
"range": { "min": 1, "max": null },
|
| 42 |
+
"type": "integer",
|
| 43 |
+
"required": true
|
| 44 |
+
},
|
| 45 |
+
"epochs": {
|
| 46 |
+
"text": "Número de épocas",
|
| 47 |
+
"Help": "Quantidade de épocas de treinamento.",
|
| 48 |
+
"default": 20,
|
| 49 |
+
"range": { "min": 1, "max": 1000 },
|
| 50 |
+
"type": "integer",
|
| 51 |
+
"required": true
|
| 52 |
+
},
|
| 53 |
+
"learning_rate": {
|
| 54 |
+
"text": "Taxa de aprendizado",
|
| 55 |
+
"Help": "Taxa usada pelo otimizador.",
|
| 56 |
+
"default": 0.0005,
|
| 57 |
+
"range": { "min": 0.000001, "max": 1.0 },
|
| 58 |
+
"type": "float",
|
| 59 |
+
"required": true
|
| 60 |
+
},
|
| 61 |
+
"weight_decay": {
|
| 62 |
+
"text": "Decaimento de peso",
|
| 63 |
+
"Help": "Regularização L2 usada pelo otimizador.",
|
| 64 |
+
"default": 0.0001,
|
| 65 |
+
"range": { "min": 0.0, "max": 0.1 },
|
| 66 |
+
"type": "float",
|
| 67 |
+
"required": false
|
| 68 |
+
},
|
| 69 |
+
"optimizer": {
|
| 70 |
+
"text": "Otimizador",
|
| 71 |
+
"Help": "Otimizador usado no treinamento.",
|
| 72 |
+
"default": "adam",
|
| 73 |
+
"type": "string",
|
| 74 |
+
"required": true
|
| 75 |
+
},
|
| 76 |
+
"d_model": {
|
| 77 |
+
"text": "Dimensão do Embedding",
|
| 78 |
+
"Help": "Dimensão interna das camadas do Transformer.",
|
| 79 |
+
"default": 64,
|
| 80 |
+
"range": { "min": 16, "max": 512 },
|
| 81 |
+
"type": "integer",
|
| 82 |
+
"required": false
|
| 83 |
+
},
|
| 84 |
+
"max_seq_len": {
|
| 85 |
+
"text": "Tamanho máximo do SMILES",
|
| 86 |
+
"Help": "Comprimento máximo de caracteres para truncamento/padding do SMILES.",
|
| 87 |
+
"default": 120,
|
| 88 |
+
"range": { "min": 30, "max": 500 },
|
| 89 |
+
"type": "integer",
|
| 90 |
+
"required": false
|
| 91 |
+
},
|
| 92 |
+
"n_augmentations": {
|
| 93 |
+
"text": "Aumento de dados (SMILES)",
|
| 94 |
+
"Help": "Quantidade de SMILES aleatórios gerados por molécula no treino via RDKit (1 = sem aumento).",
|
| 95 |
+
"default": 5,
|
| 96 |
+
"range": { "min": 1, "max": 20 },
|
| 97 |
+
"type": "integer",
|
| 98 |
+
"required": false
|
| 99 |
+
},
|
| 100 |
+
"dropout": {
|
| 101 |
+
"text": "Dropout",
|
| 102 |
+
"Help": "Taxa de dropout aplicada entre camadas.",
|
| 103 |
+
"default": 0.1,
|
| 104 |
+
"range": { "min": 0.0, "max": 1.0 },
|
| 105 |
+
"type": "float",
|
| 106 |
+
"required": false
|
| 107 |
+
}
|
| 108 |
+
},
|
| 109 |
+
"test": {
|
| 110 |
+
"batch_size": {
|
| 111 |
+
"text": "Tamanho do batch",
|
| 112 |
+
"Help": "Tamanho do batch usado na avaliação.",
|
| 113 |
+
"default": 64,
|
| 114 |
+
"range": { "min": 1, "max": null },
|
| 115 |
+
"type": "integer",
|
| 116 |
+
"required": true
|
| 117 |
+
}
|
| 118 |
+
},
|
| 119 |
+
"predict": {
|
| 120 |
+
"batch_size": {
|
| 121 |
+
"text": "Tamanho do batch",
|
| 122 |
+
"Help": "Tamanho do batch usado na predição.",
|
| 123 |
+
"default": 64,
|
| 124 |
+
"range": { "min": 1, "max": null },
|
| 125 |
+
"type": "integer",
|
| 126 |
+
"required": true
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
}
|
model/main.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
from typing import Any, Dict
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 10 |
+
|
| 11 |
+
from base_main import run_pipeline # noqa: E402
|
| 12 |
+
from dataset import TrainingDataset, tokenize_smiles # noqa: E402
|
| 13 |
+
from model import create_model # noqa: E402
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def smiles_predict_input_loader(
|
| 17 |
+
predict_dir: str,
|
| 18 |
+
predict_cfg: Dict[str, Any],
|
| 19 |
+
metadata: Dict[str, Any],
|
| 20 |
+
) -> Dict[str, Any]:
|
| 21 |
+
"""Carrega CSV/XLSX no modo predict e tokeniza a coluna de SMILES."""
|
| 22 |
+
input_file = predict_cfg.get("input_file")
|
| 23 |
+
if not input_file:
|
| 24 |
+
raise ValueError("Campo 'input_file' ausente no predict_config.json")
|
| 25 |
+
|
| 26 |
+
input_path = os.path.join(predict_dir, input_file)
|
| 27 |
+
if not os.path.isfile(input_path):
|
| 28 |
+
raise FileNotFoundError(f"Arquivo de entrada não encontrado: {input_path}")
|
| 29 |
+
|
| 30 |
+
ext = os.path.splitext(input_file)[-1].lower()
|
| 31 |
+
df_input = (
|
| 32 |
+
pd.read_excel(input_path) if ext in (".xlsx", ".xls") else pd.read_csv(input_path)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
feature_cols = metadata.get("features") or []
|
| 36 |
+
smiles_col = feature_cols[0] if feature_cols else next(
|
| 37 |
+
(c for c in df_input.columns if "smiles" in c.lower()), None
|
| 38 |
+
)
|
| 39 |
+
if not smiles_col or smiles_col not in df_input.columns:
|
| 40 |
+
raise ValueError("Coluna SMILES não encontrada no arquivo de predição.")
|
| 41 |
+
|
| 42 |
+
max_len = 120
|
| 43 |
+
X_tokens = tokenize_smiles(df_input[smiles_col].astype(str).tolist(), max_len=max_len)
|
| 44 |
+
|
| 45 |
+
return {
|
| 46 |
+
"X": X_tokens,
|
| 47 |
+
"input_size": max_len,
|
| 48 |
+
"df_input": df_input,
|
| 49 |
+
"input_file": input_file,
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
sys.exit(
|
| 55 |
+
run_pipeline(
|
| 56 |
+
dataset_cls=TrainingDataset,
|
| 57 |
+
model_factory=create_model,
|
| 58 |
+
predict_input_loader=smiles_predict_input_loader,
|
| 59 |
+
)
|
| 60 |
+
)
|
model/model.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from typing import Any, Dict, List, Optional
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.optim as optim
|
| 12 |
+
from torch.utils.data import DataLoader
|
| 13 |
+
|
| 14 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 15 |
+
from base_model import BaseModel # noqa: E402
|
| 16 |
+
from utils import emit_progress # noqa: E402
|
| 17 |
+
from dataset import VOCAB_SIZE # noqa: E402
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class _TransformerCNN(nn.Module):
|
| 21 |
+
"""Arquitetura híbrida: Transformer Encoder + 1D Highway CNN (CharNN)."""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
vocab_size: int,
|
| 26 |
+
max_seq_len: int,
|
| 27 |
+
d_model: int,
|
| 28 |
+
num_classes: int,
|
| 29 |
+
dropout: float = 0.1,
|
| 30 |
+
) -> None:
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.d_model = d_model
|
| 33 |
+
self.embedding = nn.Embedding(vocab_size, d_model, padding_idx=0)
|
| 34 |
+
self.pos_embedding = nn.Embedding(max_seq_len, d_model)
|
| 35 |
+
|
| 36 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 37 |
+
d_model=d_model,
|
| 38 |
+
nhead=4,
|
| 39 |
+
dim_feedforward=d_model * 2,
|
| 40 |
+
dropout=dropout,
|
| 41 |
+
batch_first=True,
|
| 42 |
+
)
|
| 43 |
+
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=2)
|
| 44 |
+
|
| 45 |
+
# Camadas convolucionais 1D com diferentes tamanhos de kernel (estilo CharNN)
|
| 46 |
+
self.convs = nn.ModuleList([
|
| 47 |
+
nn.Conv1d(in_channels=d_model, out_channels=64, kernel_size=k)
|
| 48 |
+
for k in (1, 3, 5, 7)
|
| 49 |
+
])
|
| 50 |
+
self.dropout = nn.Dropout(dropout)
|
| 51 |
+
self.fc1 = nn.Linear(64 * 4, 64)
|
| 52 |
+
self.relu = nn.ReLU()
|
| 53 |
+
self.fc_out = nn.Linear(64, num_classes)
|
| 54 |
+
|
| 55 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 56 |
+
x = x.long()
|
| 57 |
+
bsz, seq_len = x.size()
|
| 58 |
+
positions = torch.arange(0, seq_len, device=x.device).unsqueeze(0).expand(bsz, seq_len)
|
| 59 |
+
|
| 60 |
+
# 1. Estágio Transformer (Extração de Embeddings)
|
| 61 |
+
emb = self.embedding(x) * math.sqrt(self.d_model) + self.pos_embedding(positions)
|
| 62 |
+
trans_out = self.transformer(emb) # (B, L, d_model)
|
| 63 |
+
|
| 64 |
+
# 2. Estágio CharNN (Convoluções 1D + Global Max Pooling)
|
| 65 |
+
conv_in = trans_out.transpose(1, 2) # (B, d_model, L)
|
| 66 |
+
pooled_outputs = []
|
| 67 |
+
for conv in self.convs:
|
| 68 |
+
c = torch.relu(conv(conv_in))
|
| 69 |
+
pooled = torch.max(c, dim=2)[0]
|
| 70 |
+
pooled_outputs.append(pooled)
|
| 71 |
+
|
| 72 |
+
features = torch.cat(pooled_outputs, dim=1)
|
| 73 |
+
features = self.dropout(self.relu(self.fc1(features)))
|
| 74 |
+
return self.fc_out(features)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class TransformerCNN(BaseModel):
|
| 78 |
+
"""Wrapper do Transformer-CNN compatível com BaseModel."""
|
| 79 |
+
|
| 80 |
+
def build_model(self) -> nn.Module:
|
| 81 |
+
hp = self.config.get("hyperparameters", {})
|
| 82 |
+
self._d_model = int(hp.get("d_model", 64))
|
| 83 |
+
self._max_seq_len = int(hp.get("max_seq_len", self.input_size or 120))
|
| 84 |
+
self._dropout = float(hp.get("dropout", 0.1))
|
| 85 |
+
|
| 86 |
+
self.device = torch.device(
|
| 87 |
+
"cuda"
|
| 88 |
+
if torch.cuda.is_available() and self.config.get("use_cuda", True)
|
| 89 |
+
else "cpu"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
model = _TransformerCNN(
|
| 93 |
+
vocab_size=VOCAB_SIZE,
|
| 94 |
+
max_seq_len=self._max_seq_len,
|
| 95 |
+
d_model=self._d_model,
|
| 96 |
+
num_classes=self.num_classes,
|
| 97 |
+
dropout=self._dropout,
|
| 98 |
+
).to(self.device)
|
| 99 |
+
|
| 100 |
+
self.criterion = nn.CrossEntropyLoss()
|
| 101 |
+
return model
|
| 102 |
+
|
| 103 |
+
def train_model(
|
| 104 |
+
self,
|
| 105 |
+
train_loader: DataLoader,
|
| 106 |
+
val_loader: Optional[DataLoader],
|
| 107 |
+
epochs: int,
|
| 108 |
+
lr: float,
|
| 109 |
+
**kwargs: Any,
|
| 110 |
+
) -> Dict[str, Any]:
|
| 111 |
+
hp = self.config.get("hyperparameters", {})
|
| 112 |
+
epochs = int(hp.get("epochs", epochs))
|
| 113 |
+
lr = float(hp.get("learning_rate", lr))
|
| 114 |
+
weight_decay = float(hp.get("weight_decay", 0.0001))
|
| 115 |
+
optimizer_name = str(hp.get("optimizer", "adam")).lower()
|
| 116 |
+
|
| 117 |
+
optimizer = self._build_optimizer(optimizer_name, lr, weight_decay)
|
| 118 |
+
|
| 119 |
+
history: Dict[str, Any] = {
|
| 120 |
+
"train_loss": [], "train_acc": [],
|
| 121 |
+
"val_loss": [], "val_acc": [],
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
n_batches = max(len(train_loader), 1)
|
| 125 |
+
total_train_steps = max(epochs * n_batches, 1)
|
| 126 |
+
best_val_acc = -float("inf")
|
| 127 |
+
best_epoch = -1
|
| 128 |
+
|
| 129 |
+
for epoch in range(1, epochs + 1):
|
| 130 |
+
self.model.train()
|
| 131 |
+
run_loss = 0.0
|
| 132 |
+
correct = 0
|
| 133 |
+
total = 0
|
| 134 |
+
|
| 135 |
+
for X, y in train_loader:
|
| 136 |
+
X = X.to(self.device)
|
| 137 |
+
y = y.to(self.device)
|
| 138 |
+
|
| 139 |
+
optimizer.zero_grad()
|
| 140 |
+
logits = self.model(X)
|
| 141 |
+
loss = self.criterion(logits, y)
|
| 142 |
+
loss.backward()
|
| 143 |
+
optimizer.step()
|
| 144 |
+
|
| 145 |
+
run_loss += float(loss.item()) * X.size(0)
|
| 146 |
+
preds = logits.argmax(dim=1)
|
| 147 |
+
correct += int((preds == y).sum().item())
|
| 148 |
+
total += int(y.size(0))
|
| 149 |
+
|
| 150 |
+
global_step = (epoch - 1) * n_batches
|
| 151 |
+
emit_progress(int(global_step * 100 / total_train_steps), total_train_steps)
|
| 152 |
+
|
| 153 |
+
train_loss = run_loss / max(total, 1)
|
| 154 |
+
train_acc = correct / max(total, 1)
|
| 155 |
+
history["train_loss"].append(round(train_loss, 6))
|
| 156 |
+
history["train_acc"].append(round(train_acc, 6))
|
| 157 |
+
|
| 158 |
+
val_loss, val_acc = (float("nan"), float("nan"))
|
| 159 |
+
if val_loader is not None:
|
| 160 |
+
val_metrics = self.evaluate(val_loader)
|
| 161 |
+
val_loss = val_metrics["loss"]
|
| 162 |
+
val_acc = val_metrics["accuracy"]
|
| 163 |
+
if val_acc > best_val_acc:
|
| 164 |
+
best_val_acc = val_acc
|
| 165 |
+
best_epoch = epoch
|
| 166 |
+
|
| 167 |
+
history["val_loss"].append(round(val_loss, 6))
|
| 168 |
+
history["val_acc"].append(round(val_acc, 6))
|
| 169 |
+
|
| 170 |
+
print(
|
| 171 |
+
f"Epoch [{epoch:>3}/{epochs}] "
|
| 172 |
+
f"train_loss={train_loss:.4f} train_acc={train_acc:.4f} "
|
| 173 |
+
f"val_loss={val_loss:.4f} val_acc={val_acc:.4f}"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
history["best_epoch"] = best_epoch
|
| 177 |
+
history["best_val_acc"] = round(best_val_acc, 6) if best_epoch > 0 else None
|
| 178 |
+
self.history = history
|
| 179 |
+
return history
|
| 180 |
+
|
| 181 |
+
def evaluate(self, data_loader: DataLoader) -> Dict[str, float]:
|
| 182 |
+
self.model.eval()
|
| 183 |
+
loss_sum = 0.0
|
| 184 |
+
correct = 0
|
| 185 |
+
total = 0
|
| 186 |
+
with torch.no_grad():
|
| 187 |
+
for X, y in data_loader:
|
| 188 |
+
X = X.to(self.device)
|
| 189 |
+
y = y.to(self.device)
|
| 190 |
+
logits = self.model(X)
|
| 191 |
+
loss = self.criterion(logits, y)
|
| 192 |
+
loss_sum += float(loss.item()) * X.size(0)
|
| 193 |
+
preds = logits.argmax(dim=1)
|
| 194 |
+
correct += int((preds == y).sum().item())
|
| 195 |
+
total += int(y.size(0))
|
| 196 |
+
return {
|
| 197 |
+
"loss": loss_sum / max(total, 1),
|
| 198 |
+
"accuracy": correct / max(total, 1),
|
| 199 |
+
"n": total,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
def predict(self, inputs: Any) -> np.ndarray:
|
| 203 |
+
self.model.eval()
|
| 204 |
+
with torch.no_grad():
|
| 205 |
+
if isinstance(inputs, DataLoader):
|
| 206 |
+
outs: List[np.ndarray] = []
|
| 207 |
+
for batch in inputs:
|
| 208 |
+
X = batch[0] if isinstance(batch, (tuple, list)) else batch
|
| 209 |
+
X = X.to(self.device)
|
| 210 |
+
outs.append(self.model(X).argmax(dim=1).cpu().numpy())
|
| 211 |
+
return np.concatenate(outs, axis=0)
|
| 212 |
+
if isinstance(inputs, np.ndarray):
|
| 213 |
+
X = torch.from_numpy(inputs.astype(np.int64)).to(self.device)
|
| 214 |
+
elif isinstance(inputs, torch.Tensor):
|
| 215 |
+
X = inputs.long().to(self.device)
|
| 216 |
+
else:
|
| 217 |
+
X = torch.tensor(inputs, dtype=torch.long).to(self.device)
|
| 218 |
+
if X.ndim == 1:
|
| 219 |
+
X = X.unsqueeze(0)
|
| 220 |
+
return self.model(X).argmax(dim=1).cpu().numpy()
|
| 221 |
+
|
| 222 |
+
def save_model(self, filename: str) -> str:
|
| 223 |
+
path = os.path.join(self.model_dir, filename)
|
| 224 |
+
torch.save(
|
| 225 |
+
{
|
| 226 |
+
"state_dict": self.model.state_dict(),
|
| 227 |
+
"input_size": self.input_size,
|
| 228 |
+
"num_classes": self.num_classes,
|
| 229 |
+
"d_model": self._d_model,
|
| 230 |
+
"max_seq_len": self._max_seq_len,
|
| 231 |
+
"dropout": self._dropout,
|
| 232 |
+
"project_name": self.project_name,
|
| 233 |
+
},
|
| 234 |
+
path,
|
| 235 |
+
)
|
| 236 |
+
print(f"✓ Model saved to {path}")
|
| 237 |
+
return path
|
| 238 |
+
|
| 239 |
+
def load_model(self, filename: str) -> None:
|
| 240 |
+
path = filename if os.path.isabs(filename) else os.path.join(self.model_dir, filename)
|
| 241 |
+
ckpt = torch.load(path, map_location=self.device)
|
| 242 |
+
self._d_model = ckpt.get("d_model", self._d_model)
|
| 243 |
+
self._max_seq_len = ckpt.get("max_seq_len", self._max_seq_len)
|
| 244 |
+
self._dropout = ckpt.get("dropout", self._dropout)
|
| 245 |
+
self.model = _TransformerCNN(
|
| 246 |
+
vocab_size=VOCAB_SIZE,
|
| 247 |
+
max_seq_len=self._max_seq_len,
|
| 248 |
+
d_model=self._d_model,
|
| 249 |
+
num_classes=ckpt["num_classes"],
|
| 250 |
+
dropout=self._dropout,
|
| 251 |
+
).to(self.device)
|
| 252 |
+
self.model.load_state_dict(ckpt["state_dict"])
|
| 253 |
+
|
| 254 |
+
def _build_optimizer(self, name: str, lr: float, weight_decay: float) -> optim.Optimizer:
|
| 255 |
+
params = self.model.parameters()
|
| 256 |
+
if name == "sgd":
|
| 257 |
+
return optim.SGD(params, lr=lr, momentum=0.9, weight_decay=weight_decay)
|
| 258 |
+
if name == "rmsprop":
|
| 259 |
+
return optim.RMSprop(params, lr=lr, weight_decay=weight_decay)
|
| 260 |
+
return optim.Adam(params, lr=lr, weight_decay=weight_decay)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def create_model(
|
| 264 |
+
input_size: int,
|
| 265 |
+
num_classes: int,
|
| 266 |
+
project_name: str,
|
| 267 |
+
base_path: str,
|
| 268 |
+
config: Optional[Dict[str, Any]] = None,
|
| 269 |
+
) -> TransformerCNN:
|
| 270 |
+
return TransformerCNN(
|
| 271 |
+
input_size=input_size,
|
| 272 |
+
num_classes=num_classes,
|
| 273 |
+
project_name=project_name,
|
| 274 |
+
base_path=base_path,
|
| 275 |
+
framework="pytorch",
|
| 276 |
+
config=config or {},
|
| 277 |
+
)
|
model/python_version.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.10
|
model/requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
|
| 3 |
+
pandas
|
| 4 |
+
scikit-learn
|
| 5 |
+
joblib
|
| 6 |
+
torch
|
| 7 |
+
openpyxl
|
| 8 |
+
numpy
|
| 9 |
+
rdkit
|