File size: 5,015 Bytes
ca48c71 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | from __future__ import annotations
import os
import sys
from typing import List, Optional, Tuple
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader, TensorDataset
try:
from rdkit import Chem
_RDKIT_AVAILABLE = True
except ImportError:
_RDKIT_AVAILABLE = False
# Importa BaseDataset de ../base_dataset.py
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from base_dataset import BaseDataset # noqa: E402
# Vocabulário padrão de caracteres SMILES (índice 0 reservado para PAD, 1 para UNK)
SMILES_CHARS = " ^#%()+-./0123456789=@ABCDEFGHIKLMNOPRSTVXYZ[\\]abcdefgilmnoprstuy$"
CHAR_TO_IDX = {ch: idx + 2 for idx, ch in enumerate(SMILES_CHARS)}
VOCAB_SIZE = len(SMILES_CHARS) + 2
def tokenize_smiles(smiles_list: List[str], max_len: int = 120) -> np.ndarray:
"""Converte uma lista de strings SMILES em uma matriz de índices inteiros."""
arr = np.zeros((len(smiles_list), max_len), dtype=np.int64)
for i, smi in enumerate(smiles_list):
smi_str = str(smi).strip()
for j, ch in enumerate(smi_str[:max_len]):
arr[i, j] = CHAR_TO_IDX.get(ch, 1) # 1 = token desconhecido (UNK)
return arr
def augment_smiles(smiles: str, n_aug: int) -> List[str]:
"""Gera variantes não-canônicas de um SMILES usando RDKit."""
if not _RDKIT_AVAILABLE or n_aug <= 1:
return [smiles]
mol = Chem.MolFromSmiles(str(smiles))
if mol is None:
return [smiles]
variants = [Chem.MolToSmiles(mol, canonical=True)]
for _ in range(n_aug - 1):
variants.append(Chem.MolToSmiles(mol, doRandom=True))
return variants
class TrainingDataset(BaseDataset):
"""Dataset de sequências SMILES para o modelo Transformer-CNN."""
def _find_smiles_column(self) -> str:
explicit = self.metadata.get("features")
if explicit and len(explicit) > 0:
col = explicit[0]
if col not in self.df.columns:
raise ValueError(f"Coluna '{col}' não encontrada no DataFrame.")
return col
for col in self.df.columns:
if "smiles" in col.lower():
return col
raise ValueError(
"Nenhuma coluna SMILES encontrada. Defina-a em metadata['features']."
)
def build_features(self) -> None:
if self.df is None:
raise RuntimeError("self.df está vazio; load_raw_data() não rodou.")
hp = self.train_config.get("hyperparameters", {}) if self.train_config else {}
self.max_seq_len = int(hp.get("max_seq_len", 120))
smiles_col = self._find_smiles_column()
self.raw_smiles = self.df[smiles_col].astype(str).tolist()
# Mantém self.feature_columns com tamanho = max_seq_len para que
# dataset.get_num_features() passe o tamanho correto ao create_model
self.feature_columns = [f"token_{i}" for i in range(self.max_seq_len)]
self.X = tokenize_smiles(self.raw_smiles, max_len=self.max_seq_len)
def get_data_loader(
self,
batch_size: int = 32,
train_ratio: Optional[float] = None,
seed: Optional[int] = None,
) -> Tuple[DataLoader, DataLoader]:
train_ratio, seed = self._resolve_split_params(train_ratio, seed)
idx_train, idx_val = self._split_indices(train_ratio, seed)
assert self.X is not None and self.y is not None
hp = self.train_config.get("hyperparameters", {}) if self.train_config else {}
n_aug = int(hp.get("n_augmentations", 1))
# Aplica Data Augmentation apenas nos dados de treino
if n_aug > 1 and _RDKIT_AVAILABLE:
aug_smiles: List[str] = []
aug_y: List[int] = []
for idx in idx_train:
variants = augment_smiles(self.raw_smiles[idx], n_aug)
aug_smiles.extend(variants)
aug_y.extend([int(self.y[idx])] * len(variants))
X_train_np = tokenize_smiles(aug_smiles, max_len=self.max_seq_len)
y_train_np = np.array(aug_y, dtype=np.int64)
else:
X_train_np = self.X[idx_train]
y_train_np = self.y[idx_train]
X_train = torch.from_numpy(X_train_np).long()
y_train = torch.from_numpy(y_train_np).long()
X_val = torch.from_numpy(self.X[idx_val]).long()
y_val = torch.from_numpy(self.y[idx_val]).long()
bs = self._resolve_batch_size(batch_size)
train_loader = DataLoader(
TensorDataset(X_train, y_train), batch_size=bs, shuffle=True
)
val_loader = DataLoader(
TensorDataset(X_val, y_val), batch_size=bs, shuffle=False
)
print(
f" - Train samples: {len(X_train)} (aug={n_aug}x) | Val samples: {len(X_val)}"
f" | Batch size: {bs}"
)
return train_loader, val_loader |