Download model/dataset.py from ajvelasque/Transformer: direct link, hf CLI and curl.
- Browser
- Download file 5.02 kB
-
https://huggingface.co/ajvelasque/Transformer/resolve/main/model/dataset.py
- Command line
-
hf download hf://ajvelasque/Transformer/model/dataset.py
-
curl -L -o dataset.py https://huggingface.co/ajvelasque/Transformer/resolve/main/model/dataset.py
5.02 kB
| 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 |