Download xavante_work/flexnet/data_augmentation.py from PowerMachine/gru-ring-v13-9-2: direct link, hf CLI and curl.
- Browser
- Download file 4.93 kB
-
https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/data_augmentation.py
- Command line
-
hf download hf://PowerMachine/gru-ring-v13-9-2/xavante_work/flexnet/data_augmentation.py
-
curl -L -o data_augmentation.py https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/data_augmentation.py
4.93 kB
| """ | |
| data_augmentation — Estratégias de augmentação de dados para sequências | |
| (texto) e sinais contínuos (áudio, features de imagem). | |
| Implementa 5 estratégias: | |
| 1) TokenDrop — substitui tokens aleatórios por token especial [MASK] | |
| 2) SequenceSwap — troca dois segmentos da sequência (CutMix temporal) | |
| 3) SequenceMix — interpola linearmente duas sequências (Mixup temporal) | |
| 4) NoiseInject — adiciona ruído Gaussiano a features contínuas | |
| 5) TimeWarp — distorce levemente o tempo (para sinais) | |
| Equações: | |
| TokenDrop: x[i] = [MASK] com prob p | |
| SequenceSwap: x[i:i+L] ↔ x[j:j+L] para L ~ U(1, T/4) | |
| SequenceMix: x' = λ*x_a + (1-λ)*x_b, λ ~ Beta(α, α) | |
| NoiseInject: x' = x + ε, ε ~ N(0, σ²) | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| import numpy as np | |
| class TokenDrop: | |
| """Substitui tokens aleatórios por um token especial. | |
| Args: | |
| vocab_size: tamanho do vocabulário. | |
| mask_token_id: id do token [MASK] (default: vocab_size, i.e. último). | |
| p: probabilidade de substituir cada token (default 0.15, como BERT). | |
| """ | |
| def __init__(self, vocab_size: int, mask_token_id: int = None, p: float = 0.15): | |
| self.vocab_size = vocab_size | |
| self.mask_token_id = mask_token_id if mask_token_id is not None else vocab_size | |
| self.p = p | |
| def __call__(self, x: torch.Tensor) -> torch.Tensor: | |
| """x: (B, T) tensor long. Retorna tensor modificado (não in-place).""" | |
| if self.p == 0: | |
| return x | |
| mask = torch.rand_like(x, dtype=torch.float) < self.p | |
| return torch.where(mask, torch.full_like(x, self.mask_token_id), x) | |
| class SequenceSwap: | |
| """Troca dois segmentos aleatórios da sequência (CutMix temporal). | |
| Args: | |
| min_len: comprimento mínimo do segmento (default 2). | |
| max_len_ratio: comprimento máximo como fração de T (default 0.25). | |
| """ | |
| def __init__(self, min_len: int = 2, max_len_ratio: float = 0.25): | |
| self.min_len = min_len | |
| self.max_len_ratio = max_len_ratio | |
| def __call__(self, x: torch.Tensor) -> torch.Tensor: | |
| """x: (B, T) tensor long. Retorna novo tensor.""" | |
| B, T = x.shape | |
| max_len = max(self.min_len, int(T * self.max_len_ratio)) | |
| out = x.clone() | |
| for b in range(B): | |
| L = np.random.randint(self.min_len, max_len + 1) | |
| i = np.random.randint(0, T - L + 1) | |
| j = np.random.randint(0, T - L + 1) | |
| if i != j: | |
| # Use list-based swap to avoid in-place aliasing. | |
| tmp = out[b, i:i+L].clone() | |
| out[b, i:i+L] = out[b, j:j+L].clone() | |
| out[b, j:j+L] = tmp | |
| return out | |
| class SequenceMix: | |
| """Mixup temporal: interpola duas sequências (tokens via sampling). | |
| Para tokens (discretos), não dá para interpolar diretamente. | |
| Em vez disso, usa o "soft mixup": para cada posição, escolhe token de A | |
| com prob λ, de B com prob (1-λ). | |
| Args: | |
| alpha: parâmetro da distribuição Beta(α, α) (default 0.4, como Mixup). | |
| """ | |
| def __init__(self, alpha: float = 0.4): | |
| self.alpha = alpha | |
| def __call__(self, x: torch.Tensor) -> torch.Tensor: | |
| """x: (B, T). Mistura cada amostra com outra aleatória do batch.""" | |
| B, T = x.shape | |
| if self.alpha <= 0: | |
| return x | |
| lam = float(np.random.beta(self.alpha, self.alpha)) | |
| # Permuta aleatória do batch. | |
| perm = torch.randperm(B, device=x.device) | |
| x_b = x[perm] | |
| # Mask: True = usa x_a, False = usa x_b. | |
| mask = torch.rand(B, T, device=x.device) < lam | |
| return torch.where(mask, x, x_b) | |
| class NoiseInject: | |
| """Adiciona ruído Gaussiano a features contínuas. | |
| Args: | |
| sigma: desvio-padrão do ruído (default 0.05). | |
| """ | |
| def __init__(self, sigma: float = 0.05): | |
| self.sigma = sigma | |
| def __call__(self, x: torch.Tensor) -> torch.Tensor: | |
| if self.sigma == 0: | |
| return x | |
| return x + torch.randn_like(x) * self.sigma | |
| class TextAugmentor: | |
| """Pipeline de augmentação para texto (sequências de tokens). | |
| Aplica TokenDrop + (opcionalmente) SequenceSwap ou SequenceMix. | |
| """ | |
| def __init__(self, vocab_size: int, mask_token_id: int = None, | |
| p_drop: float = 0.10, p_swap: float = 0.30, p_mix: float = 0.30, | |
| mix_alpha: float = 0.4): | |
| self.token_drop = TokenDrop(vocab_size, mask_token_id, p_drop) | |
| self.seq_swap = SequenceSwap(min_len=2, max_len_ratio=0.2) | |
| self.seq_mix = SequenceMix(alpha=mix_alpha) | |
| self.p_swap = p_swap | |
| self.p_mix = p_mix | |
| def __call__(self, x: torch.Tensor) -> torch.Tensor: | |
| x = self.token_drop(x) | |
| if np.random.rand() < self.p_swap: | |
| x = self.seq_swap(x) | |
| if np.random.rand() < self.p_mix: | |
| x = self.seq_mix(x) | |
| return x | |